Detect background click in jQuery

Let's 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 the span, it triggers some kind of event (for example, to make the text bold), which is easy:

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

But now, when I click on an element, I want another event to fire (for example, to make the text normal weight). I need to somehow detect a click not inside the span element. This is very similar to the blur () event, but not for INPUT elements. I do not mind if this click is found only inside the DIV element, and not the entire BODY page, by the way.

I tried to get an event to fire on elements other than SPAN, 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 target inside the click event. Here is an example implementation of this method:

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

, , blur().

+3
6

, . :

$('span').click(function() {
    var span = $(this);
    // Mark the span active somehow (you could use .data() instead)
    span.addClass('span-active');

    $('div').click(function(e) {
        // If the click was not inside the active span
        if(!$(e.target).hasClass('span-active')) {
            span.removeClass('span-active');
            // Remove the bind as it will be bound again on the next span click
            $('div').unbind('click');
        }
    });
});

, . , ( ..).

+2

, , , stopPropagation . :

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

. onclick ? .

+4

, jQuery...

, - Javascript

document.onclick = function() {
  if(clickedOutsideElement('divTest'))
    alert('Outside the element!');
  else
    alert('Inside the element!');
}

function clickedOutsideElement(elemId) {
  var theElem = getEventTarget(window.event);

  while(theElem != null) {
    if(theElem.id == elemId)
      return false;

    theElem = theElem.offsetParent;
  }

  return true;
}

function getEventTarget(evt) {
  var targ = (evt.target) ? evt.target : evt.srcElement;

  if(targ != null) {
    if(targ.nodeType == 3)
      targ = targ.parentNode;
  }

  return targ;
}
+1

false , , div.

+1
$(':not(span)').click(function(){
    //dostuff
})
0

tabIndex, :

var node = document.createElement("span");
node.tabIndex = -1;

node.addEventListener("focus", function () {
    // clicked the element...
}, true);

node.addEventListener("blur", function () {
    // clicked away from the element...
}, true);

, , , IE. , !

, tabIndex of -1 , , . 0, , Tab Shift+Tab.

0

Source: https://habr.com/ru/post/1728365/


All Articles