vemund
vemund

Reputation: 1807

Open/hide div that is already open by clicking link

I have made a nav that opens when you click at the .products link and closes if you click anywhere on the screen. But it seems that if you click on the .product link when it is already open, it will not close. How can I do this?

$('#subnav').hide();

$(document).on('click', function(e) {
    if ( $(e.target).closest('.products').length ) {
        $("#subnav").show();
    }else if ( ! $(e.target).closest('#subnav').length ) {
        $('#subnav').hide();
    }
});

Upvotes: 0

Views: 124

Answers (3)

singe3
singe3

Reputation: 2105

You need a click event on the document to hide the block and a click event on the button to show the block. And in the event of the button, you need to stop the propagation of the document's event.

Like that :

$("div").hide();

$("button").bind("click",function(e){        
    e.stopPropagation();    
    $("div").toggle(200);
});

$(document).bind("click",function(){
    $("div").hide(200);
});

Assuming your code looks like that :

<div></div>
<button>open</button>

See example : http://jsfiddle.net/oqgpceod/1/

Aditionnaly you may add this code to prevent the block from hiding when you click on it :

$("div").bind("click",function(e){        
    e.stopPropagation();    
});

Upvotes: 2

semao
semao

Reputation: 1757

Fiddle: http://jsfiddle.net/r2h57jhu/

$(document).ready(function () {    
    $('#subnav').hide();
    $(document).click(function(e) {                    
       $('#subnav:visible').hide();        
    });    


    $('.products').click( function (e) {        
        $('#subnav:not(:visible)').show();
        e.stopPropagation();
    });
});

Upvotes: -1

4dgaurav
4dgaurav

Reputation: 11506

Demo

js

$("#subnav").hide();

$(".products").click(function (e) { //the usual behavior on click on .prducts
    $("#subnav").toggle();
    e.stopPropagation();
});

$("#subnav").click(function (e) { //ensures the #subnav will not hide on click on it
    e.stopPropagation();
});

$(document).click(function () { //ensures the #subnav will hide on click on document
    $("#subnav").hide();
});

Upvotes: 3

Related Questions