Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Bind click to all elements excluding class?

Tags:

jquery

click

am trying to bind a click to all elements that don't have a specific class.

I tried the following and after some googleing, it looks like it the right thing to do.

$('*:not(.class)').click(function() {
    alert('Clicked...');
});

$(':not(.class)').click(function() {
    alert('Clicked...');
});

Now, what I've just realised while writing this is that elements are layered on top of other elements, and all the elements under a click trigger a click too? Is this correct? I think it is as when the following code is executed I would get between 3 and 6 "clicks" per click.

$('*').click(function() {
    console.log('click');
});

Does anyone have any light to shed?

EDIT (Already): Ive just thought of a workaround, as follows:

$('*').click(function() {
    if ($(this).hasClass('class')) {
        console.log('click');
        return false;
    } else {
        console.log('click');
    }
});

LOGIC: This "class" element will be the top layered element and therefore will trigger the first click (theory-crafting) therefore is it has the class we return/break;

like image 866
Charlie Sheather Avatar asked Apr 25 '26 19:04

Charlie Sheather


1 Answers

Use stopPropagation. This will prevent all elements below the clicked item from firing as well.

$('*:not(.class)').click(function(event) {
    event.stopPropagation();
    alert('Clicked...');
});
like image 193
Dustin Laine Avatar answered Apr 27 '26 09:04

Dustin Laine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!