user2547885
user2547885

Reputation: 13

Why doesn't this piece of jQuery code work?

Just the first function works. When I click again on the button nothing happens. The console always prints 1.

$('#mobile-menu:not(.active)').click(
  function (e) {
    $('#wrapper').addClass('show-menu');
    $(this).addClass('active');
    $('#sidebar').show();
    e.preventDefault();
    console.log(1);
  }
);
$('#mobile-menu.active').click(
  function (e) {
    $('#wrapper').removeClass('show-menu');
    $(this).removeClass('active');
    $('#sidebar').hide();
    e.preventDefault();
    console.log(2);
  }
);

Upvotes: -1

Views: 118

Answers (4)

kalley
kalley

Reputation: 18462

Because you're binding directly to nothing. Adding active does not switch the event. Here's what you want:

$('#mobile-menu').click(
    function (e) {
        var notActive = ! $(this).hasClass('active');
        $('#wrapper').toggleClass('show-menu', notActive);
        $(this).toggleClass('active', notActive);
        // This is what I had originally
        //$('#sidebar')[notActive ? 'show' : 'hide']();
        $('#sidebar').toggle(notActive); // per @ᾠῗᵲᄐᶌ
        e.preventDefault();
        console.log(notActive ? 1 : 2);
    }
);

Upvotes: 6

Gabor
Gabor

Reputation: 394

Your selector $('#mobile-menu.active') is referring to something that doesn't exist yet, so your second function actually doesn't do anything.

You can achieve what you want like this:

$('#mobile-menu').click(function(){
  if($(this).hasClass('active')) {
    // Do stuff
  } else {
    // Do other stuff
  }
});

Upvotes: 0

user1864610
user1864610

Reputation:

When you assign the click handlers your selector only selects those elements that are .active and assigns a click handler to them. the other click handler finds no elements, and so is not assigned. You need one handler that performs both functions:

$('#mobile-menu').click(
  function (e) {
    e.preventDefault();
    if (!$(this).hasClass("active")) {
      $('#wrapper').addClass('show-menu');
      $(this).addClass('active');
      $('#sidebar').show();
      console.log(1);
    } else {
      $('#wrapper').removeClass('show-menu');
      $(this).removeClass('active');
      $('#sidebar').hide();
      console.log(2);
    }
  }
);

Upvotes: 0

wirey00
wirey00

Reputation: 33661

Use delegation

$('body').on('click', '#mobile-menu:not(.active)',function(){

});

$('body').on('click', '#mobile-menu.active',function(){

});

Or you can bind to the element using the ID and check if it has the class

$('#mobile-menu').click(function(){
    if($(this).hasClass('active')){

    }else{

    }    
});

Upvotes: 0

Related Questions