Spry

Run the Spry Element Selector on page load

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.

  1. Link the Spry Element Selector to your Spry page.
    <script src="includes/SpryDOMUtils.js" lang="text/javascript" type="javascript">
    ...
    <body>
    <div id="Accordion1" class="Accordion">
    ...
    </div>
    <div id="Accordion2" class="Accordion">
    ...
    </div>
    ...
  2. Create a new blank JavaScript file and save it as myFunctions.js.
  3. In the new JavaScript file, add a function block.
    function myFunction(){
    }
  4. 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();"

  5. 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);
  6. Lastly, link the myFunctions.js file to your Spry page.
    <script src="includes/SpryDOMUtils.js" lang="text/javascript" type="javascript">
    <script src="myFunctions.js" lang="text/javascript" type="javascript">