views:

64

answers:

4

i have an menu with some values and i got someting hidden and while click on more button it shows like google more menu... if it is clicked out it is not hiding till the more menu is clicked once again

<a href="javascript:;" onClick="toggle('one');">More<small>▼</small></a><div class="more list" id="one" style="display:none"><a href="#">test</a> <span style="color:#329">|</span> <a href="#">test1</a> <span style="color:#169">|</span> <a href="#">test4</a></div></div>

Script:

function toggle(one)
{
  var o=document.getElementById(one);   
  o.style.display=(o.style.display=='none')?'block':'none'; 
}

how to make it close while the mosuse clicks on any other place other than the menus

+3  A: 

Use the onblur event .

NM
A: 

I see you've tagged this with jQuery, if that is an option, you can clear up the link a bit, like this:

<a href="#" class="more_link">More<small>▼</small></a>

And use unobtrusive script combined with event bubbling to your advantage, like this:

$(function() {
  $(".more_link").click(function(e) {
    $(this).next(".more").toggle();
    e.stopPropagation();
  });​​
  $(".more").click(function(e) {
    e.stopPropagation();
  });
  $(document).click(function() {
    $(".more").hide();
  });​
});

You can test it out here, this only closes the menu if you clicked neither the menu of the toggle, e.g. clicking one of the test links will not close it. If you want it to, just remove the $(".more").click(function(e) { e.stopPropagation(); }); portion.

It uses event.stopPropagation() to stop the click from bubbling up to document, which if happens (and would if you clicked anything else) triggers its click handler, closing all the .more elements.

Nick Craver
A: 

I wouldn't use onBlur because it's not a good accessibility approach (for example if the user is using tab to navigate the page).

Look at this solution instead: http://stackoverflow.com/questions/533323/jquery-click-event-for-document-but-ignore-a-div

Peter Forss
A: 
Nirvana Tikku