rizzledon rizzledon - 1 month ago 16
HTML Question

Show div once clicked and hide when clicking outside

I'm trying to show the #subscribe-pop div once a link is clicked and hide it when clicking anywhere outside it. I can get it to show and hide if I change the:

$('document').click(function() {


TO

$('#SomeOtherRandomDiv').click(function() {


HTML:

<div id="footleft">
<a href="#" onclick="toggle_visibility('subscribe-pop');">Click here to show div</a>
<div id="subscribe-pop"><p>my content</p></div>
</div>


Script:

<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById("subscribe-pop");
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
}

$('document').click(function() {
$('#subscribe-pop').hide(); //Hide the menus if visible
});

$('#subscribe-pop').click(function(e){
e.stopPropagation();
});
</script>

Answer Source

You have to stop the event propagation in your container ('footleft' in this case), so the parent element don't notice the event was triggered.

Something like this:

HTML

 <div id="footleft">
    <a href="#" id='link'>Click here to show div</a>
    <div id="subscribe-pop"><p>my content</p></div>
 </div>

JS

 $('html').click(function() {
    $('#subscribe-pop').hide();
 })

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

 $('#link').click(function(e) {
     $('#subscribe-pop').toggle();
 });

See it working here.