-1

What I am trying to do is check if a class is active with hasClass. If it is active and then the wrapper is clicked remove that class from the wrapper again.

This is what I have to remove the class:

 $(function() {
    $('.toggle-nav').click(function() {
        // Calling a function in case you want to expand upon this.
        toggleNav();

        $('#site-wrapper.show-nav').click(function (){
            $(this).removeClass('show-nav');
        });
        console.log('it worked');
    });
});

But this code is removing the class as soon as it is clicked without checking "if" it is present. Even if it is not present, it removes it.

The

AntonB
  • 2,724
  • 1
  • 31
  • 39
  • Binding an event handler inside another event handler is probably not what you want. *"Even if it is not present, it removes it."* How can something be removed if it doesn't exist? That doesn't make any sense. – Felix Kling Jul 17 '14 at 03:23
  • what I meant was, the button to add the class "show-nav" is contained inside "site-wrapper". So because we are clicking inside site-wrapper and the button is inside that div it is firing both events. – AntonB Jul 17 '14 at 03:25
  • Then stop the even from propagating. http://stackoverflow.com/q/1398582/218196 – Felix Kling Jul 17 '14 at 03:26
  • ah thank you, that is what I was seeking, if you post the answer i will accept. – AntonB Jul 17 '14 at 03:30
  • Duplicate of [Prevent execution of parent event handler](http://stackoverflow.com/q/1398582/218196) – Felix Kling Jul 17 '14 at 03:32
  • tried searching before my post but to no avail, can't delete my post now that it has answers... :( – AntonB Jul 17 '14 at 03:53

3 Answers3

0

Have the if statement within the click function

    $('#site-wrapper').click(function (){
       if ($('#site-wrapper').hasClass('show-nav')) {
         $('#site-wrapper').removeClass('show-nav');
       }
    })
ajhanna88
  • 88
  • 6
0

Try this:

$('#site-wrapper').click(function () {
    if ($(this).hasClass('show-nav')) {
        $(this).removeClass('show-nav');
    } else {
        $(this).addClass('show-nav');
    }
});

JSFiddle Demo

imbondbaby
  • 6,351
  • 3
  • 21
  • 54
0
    $('#site-wrapper.show-nav').click(function (){
        $(this).removeClass('show-nav');
    });
PeterKA
  • 24,158
  • 5
  • 26
  • 48