Thursday, July 28, 2011

Javascript Tricks

Use anonymous function in setInterval, setTimeOut if we want to pass parameter to it..
for example,


function SlideShow($obj, opts) {    
        //Set the opacity of all images to 0
        $obj.find('li').css({ opacity: 0.0, marginLeft: opts.photoWidth});      

        //Get the first image and display it (set it to full opacity)                  
        $obj.find('li:first').css({ opacity: 1.0, marginLeft: 0 });                      
       
        //Call the gallery function to run the slideshow  
        //put a new variable COFtimer into the $obj object, this is because each slideshow should have its own timer
        $obj.COFtimer = setInterval(function(){gallery($obj, opts);}, opts.interval);

        //pause the slideshow on mouse over
        $obj.hover(
                function () {
                    clearInterval($obj.COFtimer);
                },
                function () {
                    $obj.COFtimer = setInterval(function(){gallery($obj, opts);}, opts.interval);
                }
            );
    }


This is a function from one of my own Jquery plugins which I recently implemented for slideshow of pictures. In the future I will write another blog about this plugin.
In the highlighted code,  $obj and opts are two parameter passed to gallery function.
Also note that in this case, I utilized javascript enclosure feature to pass these two parameters to function gallery().
Another javascript feature I utilized and really loved is I dynamically added a new variable "COFtimer" into $obj. This way each slideshow object ($obj) will have its own timer object and won't interfere each other's timer.

No comments:

Post a Comment