Skip to content Skip to sidebar Skip to footer

How To Use A Global Selector To Respond To All Click Events Except On One Element?

If I have a button:

Solution 1:

You could use the :not selector:

$('button:not(#button1)').click(function(){
  //Do something
});

The above selector will match all the button elements, except the one with id = "button1".

If you want really to select all the elements under the body tag, you can use the "All" (*) selector, and also exclude the elements with :not(selector) or .not(expr):

$('body *:not(#button1)').click(function(){
  //Do something
});

Or

$('body *').not('#button1').click(function(){
  //Do something
});

If you do so, you could have some event bubbling or propagation issues, you can handle this with the event.stopPropagation function.

Solution 2:

I know you have accepted the answer above but I would advise strongly against this. You can use event delegation to do what you want with a lot less overhead to the dom.

I know .live() exists but too many live handlers also impact performance. I prefer event delegation old style.

Demo here

$(function(){
    $('body').click( clickFn );
  });

  functionclickFn( ev ) {

    if (ev.target.id != 'button1' ){
       //do your stuffconsole.log('not a #button1 click');
    }

  }

Solution 3:

The current CSS 3 Selectors Candidate Recommendation defines the :root pseuedo class.

The :root pseudo-class represents an element that is the root of the document. In HTML 4, this is always the HTML element.

You could attach an event listener to the root and then check which element received the click. If it's the element you want to ignore return, otherwise do whatever it is you want to do.

Post a Comment for "How To Use A Global Selector To Respond To All Click Events Except On One Element?"