Click elsewhere on the page to hide two ideas for the div

  • 2020-03-29 23:47:34
  • OfStack

Thinking a

The first way of thinking is in two steps

Step 1: bind the event handler to the click event of the document so that it hides the div

Step 2: bind the event handler to the div click event to prevent the event from bubbling and bubbling into the document, which is hidden by calling the document's onclick method.
 
<script type="text/javascript"> 
function stopPropagation(e) { 
if (e.stopPropagation) 
e.stopPropagation(); 
else 
e.cancelBubble = true; 
} 

$(document).bind('click',function(){ 
$('#test').css('display','none'); 
}); 

$('#test').bind('click',function(e){ 
stopPropagation(e); 
}); 
</script> 

So that when you click on a non-div area of the page, the onclick method of the document will be called directly or layer upon layer bubble to hide the div, and when you click on the div or its children, the event will always bubble the div itself, which will prevent the event to continue to bubble, instead of calling doument's onclick method to cause the div to be hidden, thus fulfilling our requirements.

Idea 2

As we mentioned before, when an event is triggered on the DOM, an event object event will be generated. This object contains all the information related to the event, including the element and event type of the event, etc. The parameter passed by the click event handler of div in line 1 is the event object. There are several different ways to access the event object in IE, depending on how you specify the event handler. When you add an event handler directly to a DOM element, the event object exists as an attribute of the window object.

The event object contains an important attribute: target(W3C)/srcElement(IE), which identifies the original element that triggered the event. We can directly bind the event handler to the click event of the document, and in the event handler we can determine whether the event source is the div element of id==test or its children, if so the method return does nothing, and if not we can hide the div.
 
<script type="text/javascript"> 
$(document).bind('click',function(e){ 
var e = e || window.event; //Browser compatibility
var elem = e.target || e.srcElement; 
while (elem) { //Loop to the node, to prevent clicking is div child elements
if (elem.id && elem.id=='test') { 
return; 
} 
elem = elem.parentNode; 
} 

$('#test').css('display','none'); //Instead of clicking on a div or its children
}); 
</script> 

So when you click anywhere on the page, you bubble up to the click event of the document. The event handler determines whether the source of the event is a div with id==test or its child elements.

Related articles: