I am using jQuery 1.7.2 and what I'm trying to do is fire onmouseover
on one div (with class active
), but on onmouseout
change this class to inactive
and class of second div switch from inactive
to active
. After this I expect that onmouseover will be now fired on second div (I am even using .on()
so it should be live), but it won't. Here is my code:
HTML
<div class="myDiv active first"></div> <div class="myDiv inactive second"></div>
JavaScript
$(document).ready(function () {
$(".active").on("mouseover", function () {
$("#output").text("mouseover fired!");
});
$(".active").on("mouseout", function () {
$("#output").text("");
$(".first").addClass("inactive").removeClass("active");
$(".second").addClass("active").removeClass("inactive");
});
});
And here is jsFiddle for it. You can see in developer tools that the class is switched correctly, but event is still fired on first one.
I am even using
.on()
so it should be live
Nope, .on()
only has the event delegation effect when passed a descendant selector argument:
$(document).on("mouseover", ".active", function () {
Instead of document
, you may use the closest static .active
container element for better performance.
Without the descendant selector argument, jQuery will directly attach event handlers only to the elements matched in the jQuery object $('.active')
at the time it executes, exactly as the shorthand .mouseover(fn)
and the older .bind('mouseover', fn)
methods would.