Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: passing variables in hover() function?

Can I pass a variable in hover()?

As in the script below, I don't want to declare the same variable twice var target = xxx and I don't want to make this variable a global target = xxx bcos I have other function using this variable name - 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 the var like this },function (target) {, of course it is wrong, but any other method to pass this var?

thanks.

like image 583
Run Avatar asked Nov 26 '10 17:11

Run


1 Answers

The short version is just to toggle here:

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

To have it available in each handler (as a more general solution) define it outside when looping (using .each() for example), like this:

$('.image-profile').each(function() {
    var target = $('.button-change-image-profile',this);
    $(this).hover(function () {
        target.show();
    },function () {
        target.hide();
    });
});
like image 154
Nick Craver Avatar answered Oct 27 '22 11:10

Nick Craver