Reputation: 1455
I have 2 divs [id1, id2] with the same class 'orig' and one div [id3] with 'orig2'. On mouseover on any .orig makes all the divs[id1, id2] pink, and on .orig2 makes div[id3] becomes green.
<div id="id1" class="orig">Some Text</div>
<div id="id2" class="orig">Second Div of name 1</div>
<div id="id3" class="orig2">Third div</div>
<input type="button" id="btn1" value="CLICK ME" />
Jquery on roll over
$('.orig').on('mouseenter',function () {
$('.orig').css('background-color', '#e31b3f');
});
$('.orig').on('mouseleave',function () {
$('.orig').css('background-color', '#7d7d7d');
});
$('.orig2').on ('mouseenter', function () {
$('.orig2').css('background-color', '#80bd3c');
});
$('.orig2').on('mouseleave',function () {
$('.orig2').css('background-color', '#464646');
});
Now on a button click I am removing orig2 class from the div id3 and adding orig class to it. So now ideally when I scroll over id3 div, it should become pink along with id1 and id2. But this is not happening. When I scroll over id1 or id2, id3 becomes pink, indicating that .orig class was successfully added. But scrolling over id3 does nothing.
$('#btn1').on('click', function () {
$('#name2').addClass('orig');
$('#id3').removeClass('orig2');
});
This is the jsFiddle link : http://jsfiddle.net/monologish/Eprym/
This is a simplified version of my problem, I tried adding a completely new div within the holder div, but nothing changed. I don't understand why this is happening.
Upvotes: 0
Views: 927
Reputation: 318222
Event handlers are attached to the elements matching the selector at the time the handler is bound, so changing an elements class will not remove old event handlers, or make event handlers previously attached to the new class start working. For that you would have to reattach the event handler to the new elements matching the selector again, or use a delegated event handler attached to a parent element, that checks the selector during execution, like so:
$(document).on({
mouseenter: function () {
$('.orig').css('background-color', '#e31b3f');
},
mouseleave: function () {
$('.orig').css('background-color', '#7d7d7d');
}
}, '.orig');
Upvotes: 2