Monday, December 22, 2008

Adding Behavior To The Buttons In Widgets

Adding Behavior To The Buttons:

This behavior is controlled by some simple JavaScript, and all you need to do is put it in the right place. Look to the resource zip file you unpacked earlier to find a script folder containing a helloworld.js file. Copy this folder into the same directory as your index.html file.
The contents of the file is as follows:
// define a namespace to hold our widget specific functions,
// avoid polluting the global namespace
var helloWorld = helloWorld || {};

// function for flipping between different sides of the widget
helloWorld.flip = function ( e )
    var display = document.getElementById('front').style.display;
    if ( display == 'block' || display == '' )
        document.getElementById('front').style.display = "none";
        document.getElementById('config').style.display = "block";
        document.getElementById('config').style.display = "none";
        document.getElementById('front').style.display = "block";

// initialize the widget

window.addEventListener( 'load' , function(ev)
    // add behavior to the flip button
    }, false);

    // add behavior to the close button
    }, false);

    // add a change handler so that the widget shows whatever we input into the 
    // widget front, flip back to the front when done
        document.getElementById('hellotext').textContent = 

    // set the contents of the text field to the initial value
    document.getElementById('frontlabel').setAttribute( 'value',
        document.getElementById('hellotext').textContent );
In this code, we’ve encapsulated the functions specific to the widget in their own object, or namespace. This way the functions are not overriden if they have already been defined. We recommend you stay away from the global namespace as much as possible. The second half of the code is a function that runs when the widget is loaded and sets up the behavior of the buttons and the text field.
Now try running the widget and clicking the configuration button. The widget is flipped so that the reverse side of the widget is visable.