Dima Deplov
Dima Deplov

Reputation: 3718

function work without class that call for function

I have two classes and a function that works with one of them

$('.div-image').click(function(){                    // image zoom 
    $('#image').attr("src",img_src);

    $('.div-image').attr('class','div-image-big');

});

and html something like:

<div class="div-image">
<div id="wrapper">
<img id="image" src="image.jpg">
</div>
</div>

Why after first click on the image or (div .div-image) my class div-image is changing to div-image-big. But if we click once more the function $('.div-image').click(function(){...} will execute again. The question is why so? I don't need this behavior. I want that this function work only when class is div-image not div-image-big. Thanks.

Upvotes: 2

Views: 79

Answers (1)

Guffa
Guffa

Reputation: 700572

The event handler is bound on the element, not the class. Which elements it is bound to is decided based on the class they have at the time that the event is bound, so changing the class later doesn't change which elements have the event handler.

If you want the event handler to react to the class, you should bind a delegate to the a parent element. That way the event bubbles to the parent element, and the delegate handler will check for the class at that moment. Example:

HTML:

<div class="image-container">
  <div class="div-image">
    <div id="wrapper">
      <img id="image" src="image.jpg">
    </div>
  </div>
</div>

Javascript:

$('.image-container').on('click', '.div-image' ,function(){                    // image zoom 
  $('#image').attr("src",img_src);
  $('.div-image').attr('class','div-image-big');
});

Upvotes: 5

Related Questions