views:

131

answers:

2

Hi friends, 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.

+1  A: 

Basic Idea

  1. Wire an onclick event on body tag to hide the div.
  2. 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()
rahul
Thanks for your reply.I am using asp.net master page and i cant use body onclick event as it will be using in many other content pages.At the same time how can i find the html generated id for the div tag used in user control?Thanks in advance
Madhu
@Madhu: How to find the html generated id for the div tag: Post it as a separate question with source code example of how it is defined.
awe
Sorry for the late reply. How to stop event bubbling in javascript?
Madhu
Updated my answer.
rahul
+1  A: 

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.
  }
});
Joel L
What happens when the user clicks inside an element in the div element?
rahul