I'm taking by first babysteps in jQuery and stumbled upon a problem I can't seem to get around.
I couldn't find an article that quite described what my problem was, so I would like to try to get an answer this way.
I don't understand why my objects keep behaving like their former class. When I setup a hover action for a class, and change the class of the object by clicking, jQuery keeps doing the animation for the new class.
I used toggleClass()
and removeClass
/ addClass
without any result:
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 don't understand why the the hover action is triggered while the object has a new class.
Initialy you attach the event to the element
with the class
name. After the class
is changed the event remains on the element
.
To remove the event you can use .unbind
. To remove .hover
event you can check this answer .
A working example using .unbind
to remove the event and after to reattach it will look like in the snippet (basically is toggle hover event ):
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(event){ var $this = $(this); $this.unbind('mouseenter mouseleave'); // remove hover if( $this.hasClass('class2')) { $this.hover(wide, normal); // reattach hover } $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>
Use .on()
menthod to bind the event which will actually bind the event on the parent of the class.
Here is the example:
$(document).on("click", '.class1', function(){
$(this).toggleClass('class1 class2');
});
This will defiantly work...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.