user6571878
user6571878

Reputation:

Create Toggle Button Using jQuery

I want to use just ONE button to control Opening and Closing an Off-Canvas Menu. So I created a Button with OpenButton class which open menu, after clicking, I remove OpenButton class and add CloseButton class, These all work like a charm, But When I call Click Event on CloseButton It doesn't work, What is the problem ? This is my code :

$('.OpenButton').click(function() {
    $(this).addClass('CloseButton');
    $(this).removeClass('OpenButton');
});

$('.CloseButton').click(function() {
    alert('Close');
});

Upvotes: 0

Views: 1599

Answers (2)

Terry
Terry

Reputation: 66123

That is because the click event is bound at runtime. Since .CloseButton does not exist when the code is executed, no click event will be bound to it. One solution is to use $(document).on('click', '.CloseButton', function() {...}) to do that, but that is considered resource intensive and unnecessarily heavyhanded.

I would recommend that you do not change the class of the button instead. If you want to modify the style or appearance of the button when it's open/close, you can do it by adding classes instead of swapping classes, for example:

$('.button').click(function() {
    $(this).toggleClass('is-open');
});

In this case, you can you also store the state of the button in jQuery's data object. That will abstract reading the state of an object from the DOM based on it's class:

$(function() {
  $('.button').click(function() {
  
    // Store state
    if ($(this).data('is-open')) {
      $(this).data('is-open', false);
      alert('closing!');
    } else {
      $(this).data('is-open', true);
      alert('opening!');
    }
    
    // Toggle class
    $(this).toggleClass('is-open');
    $('.toggleTarget').toggleClass('is-hidden');
  });
});
.is-hidden {
  display: none;
}

.button {
  background-color: steelblue;
  color: #fff;
  display: inline-block;
  padding: 10px;
}

.button.is-open {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="button">Toggle</a>
<div class="toggleTarget is-hidden">I am content that is toggled.</div>

Upvotes: 0

David R
David R

Reputation: 15639

Since you're adding the class dynamically, you need to use event delegation to register the same with the event handler mechanism,

$(document).on('click', ".CloseButton", function() {
    alert('Close');       
});

Hope this helps!

Upvotes: 1

Related Questions