Zannix
Zannix

Reputation: 1593

jQuery - How to bind function (on hover) to element only once?

I have a div with a certain data attribute called data-id, and in jQuery I have a variable called newly_saved_itinerary which holds that ID.

I dynamically create a div with that ID, and in that same function I want to do something when a user hovers over it. However, I only want to bind this function to the element once, if the element already has an event bound, I want to do nothing.

Similar question was posted here: How to check if click event is already bound - JQuery

Someone recommended setting a CSS class the first time, and the function is not to be run if the CSS class already exists. This is what I've tried, but it doesn't work:

$('div[data-id="' + newly_saved_itinerary + '"]:not(.hover_bound)').addClass('hover_bound').bind({
    mouseenter: function (e) {
        $('div[data-id="' + newly_saved_itinerary + '"] > .it-bar-buttons').fadeToggle();
    },
    mouseleave: function (e) {
        $('div[data-id="' + newly_saved_itinerary + '"] > .it-bar-buttons').fadeToggle();
    }
});

Update:

I tried using ONE as someone suggested, but it didn't do the trick. My problem is that I create multiple elements with this function, and it seems to rebind all of them each time, instead of only binding it once per element. This is what I've tried now and after 2-3 hovers, it doesnt toggle at all:

$('div[data-id="' + newly_saved_itinerary + '"]').one({
    mouseenter: function (e) {
        $('div[data-id="' + newly_saved_itinerary + '"] > .it-bar-buttons').fadeToggle();
    },
    mouseleave: function (e) {
        $('div[data-id="' + newly_saved_itinerary + '"] > .it-bar-buttons').fadeToggle();
    }
});

Upvotes: 0

Views: 1586

Answers (2)

jvicab
jvicab

Reputation: 286

You should bind the even handler to the parent you are dynamically appending the div to, like:

$('div-parent').on('hover', 'div-inserted', function(){
    // handler code here
});

the first parameter to "on" is the event type, the second is the reference of the child element this handler will be bound to and the third is the callback function that will be executed when the event is fired.

That way the bind is made only once an not to the elements supposed to respond to but their parent, so you can dynamically delete or add as many children as you wish and they will magically respond to the event.

Upvotes: 1

Use .one()

Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

$('div[data-id="' + newly_saved_itinerary + '"]').one('hover', function () {
    //code
}, function () {
    //code
});

Upvotes: 0

Related Questions