-
Notifications
You must be signed in to change notification settings - Fork 80
Using JavaScript in Modalbox
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.
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 nativeeval()
function. There are two consequences to this:
- 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.
- 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.