Show div once clicked and hide when clicking outside

梦想与她 提交于 2019-12-04 08:02:22
Luigi Siri

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.

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(); 
        }   
    }
techfoobar

Changing $(document).click() to $('html').click() should solve the main problem.

Secondly, you do not need the toggle_visibility() function at all, you can simply do:

$('#subscribe-pop').toggle();

Ref: changed body to html as per this answer: How do I detect a click outside an element?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!