Many times, you will want some functions
to run automatically when the page loads. This example shows the
activation of the constructor scripts for 2 Accordion widgets on
the same page. We’ve also moved the JavaScript functions to an external
file so that the script is unobtrusive.
Create a new blank JavaScript file and save it as myFunctions.js.
In the new JavaScript file, add a function block.
function myFunction(){
}
Add the Spry Element Selection function to the function
block. The following example activates the Accordion widget constructors.
function myFunction(){
Spry.$$(".Accordion").forEach(function(n) { window[n.id] = new Spry.Widget.Accordion(n); });
}
The above function looks for all tags with the
"Accordion" class, which, if you are using basic Spry Accordion
code, should be on the widget container tag for all the accordions.
We’ve used the forEach function to apply the specified
function to all the instances of the selector. The window[n.id] code
acquires the ID of the selected element (Accordion1 and Accordion2)
and uses that value for the widget name. If you want to use a behavior
for that widget, for example, to open or close a panel, you use
the ID of the widget for the name: onclick="Accordion2.open();"
Next set up a listener that will execute the script after
the page is loaded. This is important because the markup needs to
exist before the constructor scripts execute. (For this reason,
constructor scripts generally come after the HTML markup in a regular
Spry page.)
// Declare a function to call when the onload event fires.
function myFunction()
{
// Find all elements in the page with a class of Accordion.
// For each matching element, create an Accordion object
// and store the object in a global variable that has the same
// name as the id of the element.
Spry.$$(".Accordion").forEach(function(n) { window[n.id] = new Spry.Widget.Accordion(n); });
}
// Register this function with Spry so that it gets called
// when the onload event fires.Spry.Utils.addLoadListener(myFunction);
Lastly, link the myFunctions.js file to your Spry page.
Comments
deejayMK said on Nov 7, 2007 at 10:17 PM : No screen name said on Jan 28, 2008 at 2:56 PM :