freaky
freaky

Reputation: 1010

jQuery pass var between event

I try to understand how I can pass a DOM betweenjQuery events.

For example, I created a simple tooltip plugin and it appends on mouseenter a div and I would like to remove on mouleave the same appended div. However if I have multiple elements which are hovered I can't select the right element to remove.

Here a simple example code:

    $(this).on('mouseenter', function() {

        $('<div class="'+options.class.split('.').join('')+'"></div>').appendTo('body').addClass(options.hoverClass.split('.').join(''));
        $tooltip = $(document).find(options.class).last();

    }).on('mouseleave', function() {

        $tooltip.first().removeClass(options.hoverClass.split('.').join(''));
        setTimeout(function() {
            $tooltip.first().remove(); // remove the right DOM appended for the element hovered
        },400);

    });

original code: http://fiddle.jshell.net/Lw4behcu/1/

EDIT: Working fiddle: http://fiddle.jshell.net/Lw4behcu/2/

Upvotes: 2

Views: 24

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

You can use the data() method to store relevant tooltip:

$(this).on('mouseenter', function () {
    var $tooltip = $('<div class="' + options.class.split('.').join('') + '"></div>').appendTo('body').addClass(options.hoverClass.split('.').join(''));
    $(this).data('tooltip', $tooltip);


}).on('mouseleave', function () {
    var $tooltip = $(this).data('tooltip').removeClass(options.hoverClass.split('.').join(''));
    setTimeout(function () {
        $tooltip.remove(); // remove the right DOM appended for the element hovered
    }, 400);

});

Upvotes: 2

Related Questions