0

I'm kind of stuck on a problem of how to stop my menu from executing the fadeOut() function. When I click the main links on my menu to open the submenu it just fades out. Here is how the code looks at the moment:

    $('a.main-menu-item').click(function(){

    if($('.rtmenu:visible')){

        $('.rtmenu').click(function(e) { e.stopPropagation(); });

        $(document).click(function() {
            $('.rtmenu').fadeOut(200);
        });
    }
})

Can anyone tell me how I can write 'if not clicked a.main-menu-item' where it says 'document'?

Much Appreciated


SOLUTION FOUND!

$('.rtmenu').click(function(e) { e.stopPropagation(); });
$('.rtmenu').mouseout(function(){ 
     $(document).one('click',function() { $('.rtmenu').fadeOut(200); }); 
 })
Nasir
  • 4,785
  • 10
  • 35
  • 39
  • 1
    see this http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element –  Aug 31 '10 at 10:50

2 Answers2

1

Have a look at Ben Alman's "outside events" plugin. It allows you to define a range of events, not just click events. With it, your code would look something like this:

$('.rtmenu').bind('clickoutside', function() {
    $(this).fadeOut(200);
});

As an aside, you shouldn't set up the bind inside the click event for the menu, this will attach another handler every time the menu option is clicked. Your code should be replace with something like:

$('a.main-menu-item').click(function(){
    // Show menu item
});
$('.rtmenu').bind('clickoutside', function() {
    $(this).fadeOut(200);
});
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • @Nasir: then you're probably not using it right. I've added an example to my post. – Andy E Aug 31 '10 at 11:18
  • Yeah tell me about it...I'm trying to integrate with ASP Classic...fippin joke. Is it not possible to change the 'document' in my existing code? – Nasir Aug 31 '10 at 11:35
  • @Nasir: `if ($('.rtmenu:visible'))` will always evaluate to true because it returns an object which, when converted to a boolean, is *true*. Like I said in my answer, you shouldn't be defining the event inside an if statement or inside another event's handler. – Andy E Aug 31 '10 at 12:10
  • SOLUTION FOUND! ----------------------------------------------------------------------------------------------------------------------------- $('.rtmenu').click(function(e) { e.stopPropagation(); }); $('.rtmenu').mouseout(function(){ $(document).one('click',function() { $('.rtmenu').fadeOut(200); }); }) – Nasir Aug 31 '10 at 12:50
0

use blur event to handle losing focus. This might help also.

Community
  • 1
  • 1
Ido Weinstein
  • 1,176
  • 8
  • 24