Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 826
rizzledon Avatar asked Apr 24 '13 13:04

rizzledon


2 Answers

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.

like image 123
Luigi Siri Avatar answered Sep 29 '22 02:09

Luigi Siri


I reckon that the asker is trying to accomplish a jquery modal type of display of a div.

Should you like to check this link out, the page upon load displays a modal div that drives your eye into the center of the screen because it dims the background.

Moreover, I compiled a short jsFiddle for you to check on. if you are allowed to use jquery with your requirements, you can also check out their site.

Here is the code for showing or hiding your pop-up div

var toggleVisibility = function (){
     if($('#subscribe-pop').is(":not(:visible)") ){
            $('#subscribe-pop').show(); 
        }else{
             $('#subscribe-pop').hide(); 
        }   
    }
like image 34
KevinIsNowOnline Avatar answered Sep 29 '22 02:09

KevinIsNowOnline