johnnyd23
johnnyd23

Reputation: 1705

Pass variable relative to the selector to multiple jQuery events

I'm looking for a way to pass a variable that is relative to the element to both mouseenter and mouseleave events. For example, if I had:

jQuery('.element').on({
    mouseenter: function () {
        var $child = jQuery(this).find('.child');
        $child.fadeIn();
    },
    mouseleave: function () {
        var $child = jQuery(this).find('.child');
        $child.fadeOut();
    }    
});

Is there a way to avoid defining the $child variable twice? I was able to figure this out using .hover(), however I am now unable to use that as I am calling it on dynamically generated elements, for which .hover() will not work.

Upvotes: 0

Views: 287

Answers (3)

Wilmer
Wilmer

Reputation: 2511

You could reuse the same function in both events, something like:

jQuery('.element').on({
    mouseenter: function () {
        handleFade("enter", jQuery(this));
    },
    mouseleave: function () {
        handleFade("leave", jQuery(this));
    }    
});

function handleFade(state, $elem){
    var $child = $elem.find('.child');
    if(state=="enter"){
        $child.fadeIn();
    } else if(state=="leave"){
        $child.fadeOut();
    }
}

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

You can use this way to delegate both events:

jQuery(document).on("mouseenter mouseleave", ".element", function(e){
    jQuery(this).find('.child').fadeToggle();
    // you can check for e.type for more complex logic    
});

The syntax to delegate with different handlers is:

jQuery(document).on({
    mouseenter: function () {
        //...
    },
    mouseleave: function () {
        //...
    }    
}, ".element");

Upvotes: 1

user123_456
user123_456

Reputation: 5805

Use something like that:

jQuery('.element').on({
    mouseenter: function (e) {
        var ele = e.currentTarget;
        ele.fadeIn();
    },
    mouseleave: function (e) {
        var ele= e.currentTarget;
        ele.fadeOut();
    }    
});

Upvotes: 1

Related Questions