Muhammed Aslam C
Muhammed Aslam C

Reputation: 887

jQuery on click event not working on toggled class

I have tried "on","live", and "delegate" methods in jQuery, but nothing seems to work.

What i want to do is when user clicks on sign in button with a class of .signin , to toggle a class named .menu-open . and then, i want alert something when i click on that button again!

$(document).ready(function() {
 $(".signin").click(function(e) {          
  e.preventDefault();
  $(".signin").toggleClass("menu-open");
});
 $('.menu-open').on('click', function() {
  alert("SUCCESS");
 });
});

Upvotes: 1

Views: 499

Answers (2)

Shakti Patel
Shakti Patel

Reputation: 3862

can you please remove this line

e.preventDefault();

preventDefault :

If this method is called, the default action of the event will not be triggered.

used this code :

$(document).ready(function() {
 $(".signin").click(function() {
  $(this).toggleClass("menu-open");
     $( ".menu-open" ).bind( "click", function() {
    alert("SUCCESS");
    });     
 });
});

working fine check here

Demo

Upvotes: 1

Ram
Ram

Reputation: 144689

That's because on the page load there is no element with class of .menu-open in the document so the query silently fails, you should delegate the event.

$(document).on('click', '.menu-open', function() {
   alert("SUCCESS");
});

Note that using a static parent element is more efficient than using document object as the target of delegation.

Upvotes: 3

Related Questions