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();
}
});