As I navigate my way through learning jQuery, I've encountered a puzzling issue that I can't seem to solve.
No existing articles seem to address my specific problem, so I am turning to this platform in hopes of finding a solution.
I'm puzzled by the fact that my objects continue to exhibit the behavior of their previous class even after changing classes. Whenever I set up a hover action for a particular class and then change the class by clicking, jQuery still executes the animation for the old class.
I've tried using both toggleClass()
and combining removeClass
/addClass
without success:
https://jsfiddle.net/biest9160/f0na6sro/
var wide = function() {
$(this).animate({ 'width': '120px' }, 200);
}
var normal = function() {
$(this).animate({ 'width': '100px' }, 200);
}
$(document).ready(function() {
$('.class1').hover(wide, normal);
$('.class1').click(function() {
$(this).toggleClass('class1 class2');
})
})
div {
width: 100px;
height: 100px;
border: 1px solid #000;
margin: auto;
}
.class2 {
background: #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box1" class="class1">box1</div>
<div id="box1" class="class1">box2</div>
<div id="box1" class="class1">box3</div>
<div id="box1" class="class1">box4</div>
I can't quite grasp why the hover action continues to trigger even after the object has a different class applied to it.