Reputation: 26281
I would like to have both a hover and remove hover event. The nodes which have this event are added dynamically, so I wish to use on(). When adding a hover event, it works great (the #second list below). For some reason when I add the off hover event, not even the add hover event will work (#first list below).
Please provide any clues. A live example is located at http://jsfiddle.net/NV7hR/
Thanks
$(document).ready(function() {
$("#first").on("hover", "a", function(event) {
$(this).parent().css("background-color", "yellow");
}, function(event) {
$(this).parent().css("background-color", "");
});
$("#second").on("hover", "a", function(event) {
$(this).parent().css("background-color", "yellow");
});
});
<body>
<ul id="first">
<li><a href="#"/>Link</a></li>
<li><a href="#"/>Link</a></li>
<li><a href="#"/>Link</a></li>
</ul>
<ul id="second">
<li><a href="#"/>Link</a></li>
<li><a href="#"/>Link</a></li>
<li><a href="#"/>Link</a></li>
</ul>
</body>
Upvotes: 0
Views: 304
Reputation:
In spite of what everyone else claims, you can indeed use 'hover'
with .on()
.
It's just that you can't pass 2 functions. You need to test the event type.
$("#first").on("hover", "a", function(e) {
$(this).css("background-color", e.type === 'mouseenter' ? "yellow" : '');
});
DEMO: http://jsfiddle.net/HxuuS/
FYI, the reason passing 2 functions caused it to not work at all is that the first handler was interpreted as the optional data
argument to on
, so it was only the second handler (the mouseleave
one) that was being bound.
Upvotes: 2
Reputation: 79830
.hover
as such is not an event. hover
is shorthand for mouseenter
and mouseleave
events. Try using like below,
$("#first").on({
mouseenter: function() {
$(this).parent().css("background-color", "yellow");
},
mouseleave: function() {
$(this).parent().css("background-color", "");
}
}, 'a');
Upvotes: 3
Reputation: 3205
Split the hover into mouseenter and mouseleave, which is what hover is shorthand for anyways.
$("#first").on("mouseenter", "a", function(event) {
$(this).parent().css("background-color", "yellow");
}).on("mouseleave", "a", function(event) {
$(this).parent().css("background-color", "");
});
Upvotes: 4