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!