Hiding div tag when the user clicks outside the div tag
I have a div tag and I am populating the search results on a custom grid, which is placed inside this divtag.
When a user click on the search button, i am displaying the results in the above mentioned div tag.
I have a requirement to close the above div tag when the user clicks outside the div tag.
It is similar to google 开发者_如何转开发search auto comlete.
Thanks in advance.
In jQuery, something like this:
$('body').click(function(ev){
if (!$(this).hasClass('your_result_container_classname') {
// code to hide result div
$('body').unbind('click'); // remove event handler. add again when results shown.
}
});
Basic Idea
- Wire an onclick event on body tag to hide the div.
- Wire an onclick event on div tag and stop event bubbling.
See Event order
To stop event bubbling
In the Microsoft model you must set the event’s cancelBubble property to true.
window.event.cancelBubble = true
In the W3C model you must call the event’s stopPropagation() method.
e.stopPropagation()
精彩评论