0

I have a 'li' that pops down when I click on a 'link' via jquery's 'click'.

Does anyone know of a clean way to do something along the lines of 'offclick'? As in, when I click off of the element, it would hide the pop down?

Thanks! Matt

Matt
  • 247
  • 1
  • 4
  • 12
  • 1
    possible duplicate of [How to detect a click outside an element?](http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element) – Felix Kling Jul 21 '11 at 07:49

3 Answers3

2

You would want to assign a click listener to the window and also assign the click listener to your link. Inside the link click listener, you'll want to stop the event propagation so it doesn't travel up the DOM tree and fire your window's click listener.

Something like this should do the trick:

$(window).click(function(){
  $('li#my_li').slideUp();
});

$('a#my_link').click(function(event){
    try
    {
        event.stopPropagation();
    }
    catch(err)
    {
        // IE does it this way
        window.event.cancelBubble=true;
    }
  $('li#my_li').slideDown();
});
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
  • (a) You need to define `event` as parameter of the event handler. (b) jQuery normalizes the `event` object. No need for special IE treatment. – Felix Kling Jul 21 '11 at 07:54
  • a) ya caught that :) , b) unless they added that feature post 1.4, it actually is required. Only reason I know is because IE ignored my `event.stopPropagation()` in my application and I had to look up why :) This was about 8 months ago, however, so I wouldn't be surprised if it's fixed in the current distro. – AlienWebguy Jul 21 '11 at 07:57
  • `event.stopPropagation()` exists since jQuery 1.0 – Felix Kling Jul 21 '11 at 07:58
  • Doesn't mean IE has been cooperating since then ;) – AlienWebguy Jul 21 '11 at 15:06
0

I guess you could look at blur, which is called when the element looses focus: ref: http://api.jquery.com/blur/

Tommy
  • 493
  • 2
  • 5
  • 16
0

You can use blur or focusout depending on your needs

JMax
  • 26,109
  • 12
  • 69
  • 88
  • I think this is what I'm looking for JMax. I'll try it out and let you know! Thanks man. – Matt Jul 21 '11 at 08:03