Skip to content

Using JavaScript in Modalbox

okonet edited this page Aug 25, 2010 · 1 revision

Introduction

This page explains how to define JS functions inside MB content correctly. Since I’ve getting a lot of feedback on this topic, I decided to write down some notes about correct usage of JavaScript inside the content which is will be loaded into the ModalBox.

Details

First of all, please read this article to get an idea of how Ajax calls are working: http://prototypejs.org/api/ajax/updater

It says regarding exactly that problem:

If you use evalScripts: true, any <script> block will be evaluated. This does not mean it will get included in the page: they won’t. Their content will simply be passed to the native eval() function. There are two consequences to this:

  1. The local scope will be that of Prototype’s internal processing function. Anything in your script declared with var will be discarded momentarily after evaluation, and at any rate will be invisible to the remainder of the page scripts.
  2. If you define functions in there, you need to actually create them, otherwise they won’t be accessible to the remainder of the page scripts. That is, the following code won’t work:
// This kind of script won't work if processed by Ajax.Updater:
function coolFunc() {
  // Amazing stuff!
}

You will need to use the following syntax:

// This kind of script _WILL_ work if processed by Ajax.Updater:
coolFunc = function() {
  // Amazing stuff!
}

Secondly, the Modalbox itslefs is trying to get the right scope back to these scripts. It is using bind(window) method to achieve that.

Clone this wiki locally