javascript - New class keeps old class behaviour -


i'm taking first babysteps in jquery , stumbled upon problem can't seem around.

i couldn't find article quite described problem was, try answer way.

i don't understand why objects keep behaving former class. when setup hover action class, , change class of object clicking, jquery keeps doing animation new class.

i used toggleclass() , removeclass/ addclasswithout 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 hover action triggered while object has new class.

initialy attach event element class name. after class changed event remains on element.

to remove event can use .unbind. remove .hover event can check this answer.

a working example using .unbind remove event , after reattach in snippet (basically 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>


Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

javascript - Blogger related post gadget image Resize s72-c [ Need Expert Help ] -