Detect background click in jQuery

Senseful picture Senseful · Jan 13, 2010 · Viewed 13.1k times · Source

Say I have the following HTML:

<div>
  <span>span text</span> div text <span>some more text</span>
</div>

I want to make it so that when I click on span, it will trigger some event (e.g. to make the text bold), that's easy:

$('span').click( ... )

But now I when I click away from the element, I want another event to trigger (e.g. to make the text normal weight). I need to detect, somehow, a click not inside the span element. This is very similar to the blur() event, but for non INPUT elements. I don't mind if this click is only detected inside the DIV element and not the entire BODY of the page, btw.

I tried to get an event to trigger in non-SPAN elements with the following:

$('div').click( ... ) // triggers in the span element
$('div').not('span').click( ... ) // still triggers in the span element
$('div').add('span').click( ... ) // triggers first from span, then div

Another solution would be to read the event's target inside the click event. Here's an example of implementing it this way:

$('div').click(function(e) {
  if (e.target.nodeName != "span")
     ...
});

I was wondering if there was a more elegant solution like blur() though.

Answer

dmonopoly picture dmonopoly · Dec 29, 2011

From what I've researched, I think the stopPropagation function is most appropriate. For example:

$("#something_clickable a").click(function(e) {
   e.stopPropagation();
})

See How do I prevent a parent's onclick event from firing when a child anchor is clicked? for a similar question.