0

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');
});
1
  • 1
    Use document on. Commented Oct 18, 2017 at 9:10

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

4 Comments

Then it opens the open menu as expected?
Yes, Thanks, I editted and added document.on for both of them and works like a charm ...
I want :), But StackOverFlow doesn't allow me to accept in 2 minutes, I'm waiting to terminate this rule ... :))), Again Thanks ...
Haha!.. Thanks! :-)
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.