raeq
raeq

Reputation: 971

How to bind click events to a different class?

So I have two click events for "button-open" and "button-close". I have one button that switches from "button-open" to "button-close" on click. So when i click it again, it should fire the event for "button-close" but instead it fires the event for "button-open" again. Demo : jsFidde

Here's my code:

<a href="#" class="button-open">Button</a>​

<script>
$(document).ready(function() {
   $(".button-open").click(function() {
      $(this).removeClass("button-open").addClass("button-close");
      alert("Open Was Clicked");
   });

   $(".button-close").click(function() {
      $(this).removeClass("button-close").addClass("button-open");
      alert("Close Was Clicked");
   });
});
</script>

Upvotes: 2

Views: 447

Answers (1)

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91349

Use on() instead of click(), since you need to bind to an element that doesn't yet exist when you initially bind it.

$(document).on('click', '.button-open', function() {
    $(this).removeClass("button-open").addClass("button-close");
    alert("Open Was Clicked");
});


$(document).on('click', '.button-close', function() {
    $(this).removeClass("button-close").addClass("button-open");
    alert("Close Was Clicked");
});

DEMO.

Upvotes: 5

Related Questions