Jquery: passing variables to hover () functions?

Can I pass a variable to hover ()?

As in the script below, I do not want to declare the same variable twice var target = xxx , and I do not want this variable to be global target = xxx bcos. I have another function using this variable name - the target.

  $('.image-profile').hover(function () { var target = $('.button-change-image-profile',this); target.show(); },function () { //var target = $('.button-change-image-profile',this); target.hide(); }); 

So, I tried to pass var like this },function (target) { course, this is wrong, but any other way to pass this var?

thanks.

+6
variables scope jquery global-variables hover
source share
4 answers

A short option is to simply switch here:

 $('.image-profile').hover(function () { $('.button-change-image-profile',this).toggle(); }); 

To make it available in each handler (as a more general solution), define it externally when looping (e.g. .each() ):

 $('.image-profile').each(function() { var target = $('.button-change-image-profile',this); $(this).hover(function () { target.show(); },function () { target.hide(); }); }); 
+6
source share

Another possible approach: save data in this / off using jQuery .data() . You save it to the mouse, you extract it to the mouse. It can be conceptually similar to using the global variable var or var from the hover function, so t can create some garbage ...

 $('.image-profile').hover(function () { var target = $('.button-change-image-profile',this); target.show(); // we save the target object into the 'target' key. $(this).data('target',target); },function () { // we retrieve the target object (a jQuery object) and then hide it. $(this).data('target').hide(); }); 

Hope this approach is not too wrong ...

+7
source share

Just define the var out of hover function.

+1
source share

I think jQuery bind might be what you want.

+1
source share

All Articles