May 19, 2013

f Comment

How Does a jQuery Function Call an External Function Correctly?

Amazon Let's say you would like to define an external JavaScript function for a jQuery function to call instead of having the jQuery function call an anonymous function. What is the correct way to call an external function within a jQuery function?

Define the external function.
First define the external function as a variable. Here's an example function you'd like to call whenever a target selector is being hovered.
var hoverFunc = function(selector){  
    $(selector).children('.d').css('left', $(selector).children('.d').siblings('img').css('left'));  
    $(selector).children('.d').stop().fadeTo(500, 0.7);  
};

Call the external function properly.
Next call this function inside an anonymous function within the jQuery function where needed. Here's an example of calling hoverFunc() whenever a selector is being hovered.
$(window).load(function(){  
    //first way: incorrect and doesn't work
    $('div.wrapper').hover(hoverFunc(this));

    //second way: correct and works    
    $('div.wrapper').hover(function(){
        hoverFunc(this);
    }); 
});
A big gotcha is the first way does NOT work. You MUST call the closure hoverFunc() inside an anonymous function.

You can still achieve code reuse this way because you only define hoverFunc() which can be used in more than one place.
That's it. All together the code looks like the following.
<script type='text/javascript'>
var hoverFunc = function(selector){  
    $(selector).children('.d').css('left', $(selector).children('.d').siblings('img').css('left'));  
    $(selector).children('.d').stop().fadeTo(500, 0.7);  
};

$(window).load(function(){     
    $('div.wrapper').hover(function(){
        hoverFunc(this);
    }); 
});
</script>
Questions? Let me know!
Please leave a comment here!
One Minute Information - by Michael Wen
ADVERTISING WITH US - Direct your advertising requests to Michael