What is wrong with this little script? (jquery noob)

IF the user clicks outside an element I want to remove a class from the element IF the element has that class. In this case it is a push menu that I want to close by removing the class that changes its left position, if the user clicks outside it.

$(document).on(‘click’, function (e){

var basket = $(“#push-basket”);

if (!basket.is(e.target) {
if(basket.hasClass(‘.show-push-menu-left’)) {


Can anyone help me do this the right way? Atm this script breaks the site.

I’m not sure, but I don’t think you have to check for existence of class… in jQuery, if the class isn’t present, it doesn’t error. You can just removeClass.


okey cool=)

Here is a bit more throughout explanation of what i want to do:

Here is the jquery i use to toggle the menu and the classes:

  $('.toggle-push-basket').on('click', function(){
      $('body, header').toggleClass('push-left');

So atm I can only close the menu by clicking the .toggle-push-basket again. But I want to be able to close it by clicking anywhere outside of #push-basket aswell.

How could I do this?

This is how my nooby jquery looks atm:

$(document).on('click', function (e){

  var basket = $("#push-basket");
  var toggleBasket = $(".toggle-push-basket");
  var toggleBody = $(".push-left");

  if (!basket.is(e.target) && !toggleBasket.is(e.target)) {


I think you’re idea is right, but I think the problem is you’re using .on() instead of .click(). You read a lot about .click() being a “shortcut” method, but it’s not really.

When you use .click() the dom elements are registered as initialization, where as with .on() they are registered dynamically at request. You’re looking for exclusiveness between the elements, so unless you have a reason to use .on() you should use .click() instead and register them in your $(document).ready(function(){});

I could be talking out of my butt and if anyone wants to correct me or clarify what I said, please do. But this is how I use them.