David
David

Reputation: 49

jQuery - Hide other divs when clicking new div

I have written this code, that shows a menu (div) when clicking another div. The problem is that when I have one of the menus open, and click the div to open a new menu (there are multiple menus looped out), the other menus do not close. This means I can open an unlimited number of menus simultaneously as long as I am not clicking outside the div/menu...

Short: I want all open menu divs to hide when clicking to open a new menu, except from the menu I just opened...

Code:

$('.commentSettings').click(function(e) {
    var id = $(this).attr('id');
    $('#mod-dropdown' + id).stop().toggle(200);
    e.stopPropagation();
    $('#mod-dropdown' + id).show();

    $(document).click(function(){
        $("#mod-dropdown" + id).hide();
    });
 });

Upvotes: 0

Views: 1005

Answers (4)

WooCaSh
WooCaSh

Reputation: 5212

This should work:

 $('.commentSettings').click(function(e) {
    var id = $(this).attr('id');
    $('#mod-dropdown' + id).stop().toggle(200);
    e.stopPropagation();
    $('#mod-dropdown' + id).show();
 });

 $(document).click(function(){
    $('[id^="#mod-dropdown"]').hide();
});

I use here jQuery attributeStartsWith selector.

More info you can find here: http://api.jquery.com/attribute-starts-with-selector/

Upvotes: 0

hjpotter92
hjpotter92

Reputation: 80629

You can have something like this:

var id = -1;
$('.commentSettings').click(function(e) {
    if( id != -1 )
        $('#mod-dropdown' + id).hide();
    var id = $(this).attr('id');
    $('#mod-dropdown' + id).stop().toggle(200);
    e.stopPropagation();
    $('#mod-dropdown' + id).show();

    $(document).click(function(){
        $("#mod-dropdown" + id).hide();
    });
});

Upvotes: 0

DF_
DF_

Reputation: 3973

If you give all divs you want to hide a class, for example menu, then you simply could pop $('.menu').hide(); at the start of the click function.

Note that you have a document ready inside the function and I don't think you wanted to put that there. The document.ready function should always appear first, and you register your event handlers inside that.

Upvotes: 1

FtLie
FtLie

Reputation: 773

I presume all menus have a common class. Use this to close all menus first. Then open the one currently clicked.

Upvotes: 0

Related Questions