0

So I have HTML and jquery code. When I frist time click on image (when it has class hide) first jquery click function exectues, but when I click on image again it won't execute other one. Why is that? I change class from hide to show,so it should execute second one.

$(document).ready(function(){

$( "#slide.hide" ).click(function() {
  $("#slide").attr("src","arrow-down-icon.png");
  $('#wrapper').slideUp(1000);
  $("#slide").removeClass("hide").addClass("show");
});

$( "#slide.show" ).click(function() {
  $("#slide").attr("src","arrow-up-icon.png");
  $('#wrapper').slideDown(1000);
  $("#slide").removeClass("show").addClass("hide");
});
  
});
<img src="arrow-up-icon.png" alt="up" height="42" width="42"  class="hide" id="slide">

<div id="wrapper">
 123
</div>
user3421357
  • 37
  • 1
  • 5
  • The event handlers are added to elements that match the selector ***when the code runs***, not later. In other words, changing the class doesn't magically make the event handlers work, all your logic should be in the event handler for `.hide`, and then you just check the elements class ***when the click happens***. – adeneo Jan 03 '16 at 21:24

1 Answers1

0

Direct binding is not a continuous process. It is used to filter matching element to attach the event handlers on. If they do not match when the binding is evaluating the handler will not be attached.

You can overcome this by using a delegate binding which will evaluate the bubbling events from children to see if the logic should process.

$( "#slide" ).parent().on('click', '#slide.show', function(){
    //will execute if the child slide has the class show
}).on('click', '#slide.hide', function(){
    //will execute if the child slide has the class hide
});

Or simply combine the two handlers

$('#slide').on('click', function(){
    var $this = $(this);

    if ($this.hasClass('hide')) {
        //do stuff
    } else {
        //do stuff
    }
});
Taplar
  • 24,788
  • 4
  • 22
  • 35