1

I have jQuery that drops a menu down when its parent is clicked on, and dismisses it when they hover away from the menu. I am wanting to change the behavior so that it only dismisses if they click somewhere else on the page, or a different menu. Is this possible?

jQuery.fn.dropdown = function () {
    return this.each(function () {
        $('.ui-dropdown-list > li > a').click(function () {
            $(this).addClass("ui-dropdown-hover");
        });

        $("ul.ui-dropdown-list > li > a").click(function () {
            $(this).parent().find("ul").show();

            $(this).parent().hover(function () {
            }, function () {
                $(this).parent().find("ul").hide();
                $(this).find('> a').removeClass("ui-dropdown-hover");
            });
        });
    });
};
Ciel
  • 16,274
  • 19
  • 101
  • 196

2 Answers2

4

Try placing a click handler on your body that will dismiss the menu. The event should propogate up to the body unless it is dismissed elsewhere.

Something like this:

$("body").click(function() {
  $(".ui-dropdown-hover").removeClass(".ui-dropdown-hover");
});
BradBrening
  • 5,300
  • 23
  • 30
  • @Stacey: This should work. But you should also remove your hover function. And for future reference, you shouldn't add an event function (like the hover function) inside a click function. – Mottie Apr 26 '10 at 04:30
0

Adding to the answer from @BradBrening: you may want to wait a short while before adding the handler, and also to unbind any earlier click handlers you've registered for doing the same thing. Otherwise if the user clicks the item again it will immediately fade away!

I did something like the following, where 'click.junk' is what jquery calls an event namespace:

$( 'body' ).unbind( 'click.junk' );

// ...code to add a DIV with ID my_new_item to the DOM...

$( '#my_new_item' ).fadeIn();
window.setTimeout( function() { 
    $( 'body' ).bind( 'click.junk', 
        function() { $( '#my_new_item' ).fadeOut() } 
    );
}, 200 );

This worked for me! (Also ref: 209029)

Community
  • 1
  • 1
Chris Winters
  • 971
  • 1
  • 5
  • 5