ditto
ditto

Reputation: 6277

jQuery: Clicking anywhere to remove class, without using $('body').on('click'

I want to remove all active classes when clicking anywhere on the screen, but if a clicked element has the .dropdown class, I would also want to toggle the .active class into that element.

// remove all .active classes when clicked anywhere
hide = true;
$('body').on("click", function () {
    if (hide) $('.dropdown').removeClass('active');
    hide = true;
});

// add and remove .active
$('body').on('click', '.dropdown', function () {

    var self = $(this);

    if (self.hasClass('active')) {
        $('.dropdown').removeClass('active');
        return false;
    }

    $('.dropdown').removeClass('active');

    self.toggleClass('active');
    hide = false;
});

I have this working with the above but I'm worried capturing a body click is overkill, and unnecessary. Is there a better solution?

jsiddle - I've set several li's to the .active class, if you click around you will see they get removed. Clicking an li will trigger toggleClass('active'), whilst still removing all .active classes.

Upvotes: 0

Views: 4307

Answers (1)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

you could try doing:

$('body').on("click", function (ev) {
    if( $(ev.target).hasClass('.dropdown') ) {
        //you clicked on .dropdown element, do something
    }
    else {
        //you clicked somewhere other than dropdown element
    }
});

Upvotes: 2

Related Questions