The King is The King is - 3 months ago 14
jQuery Question

Toggling multiple divs and also close when anywhere outside the div is clicked

I use this jQuery code to toggle a div and also make the div to close if anywhere outside the div is clicked:

$(document).ready(function(){
$('html').click(function(){
$('div').hide();
});

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

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

$('a').click(function(){
$('div').toggle();
});

})


But I have many divs which I need to run this function so I did this:

<a href="javascript:;" class="tgl" id="link-1" alt="div-1">LINK 1</a>
<a href="javascript:;" class="tgl" id="link-2" alt="div-2">LINK 2</a>
<a href="javascript:;" class="tgl" id="link-3" alt="div-3">LINK 3</a>
<div id="div-1"></div>
<div id="div-2"></div>
<div id="div-3"></div>
$(document).ready(function(){
$('html').click(function(){
$('#div-1').hide();
$('#div-2').hide();
$('#div-3').hide();
});

$('#link-1').click(function(e){
e.stopPropagation();
});
$('#link-2').click(function(e){
e.stopPropagation();
});
$('#link-3').click(function(e){
e.stopPropagation();
});

$('#div-1').click(function(e){
e.stopPropagation();
});
$('#div-2').click(function(e){
e.stopPropagation();
});
$('#div-3').click(function(e){
e.stopPropagation();
});

$('.tgl').click(function(){
altDiv = $(this).attr('alt');
$('#'+altDiv).toggle();
});

})


But it works for only the first div, the two other divs don't even toggle at all
here is a jsFiddle link. I want each
link
toggle
the
div
id
with the
alt
value. which means that if
div-1
is toggled on and
link-2
is clicked, the
div-1
will be hidden and
div-2
will show up

Answer

To shorten your code also you should use this

<a href="javascript:;" class="tgl" id="link-1" alt="div-1">LINK 1</a>
<a href="javascript:;" class="tgl" id="link-2" alt="div-2">LINK 2</a>
<a href="javascript:;" class="tgl" id="link-3" alt="div-3">LINK 3</a>
<div class="divClass" id="div-1"></div>
<div class="divClass" id="div-2"></div>
<div class="divClass" id="div-3"></div>
$(document).ready(function(){
    $('html').click(function(){
        $('#div-1').hide();
        $('#div-2').hide();
        $('#div-3').hide();
    });

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

    $('.tgl').click(function(e){
        altDiv = $(this).attr('alt');
        $('#'+altDiv).toggle();
        e.stopPropagation();
    });

})