How do I hide an element on a click event anywhere outside of the element?

拜拜、爱过 提交于 2019-12-17 02:08:29

问题


I would like to know whether this is the correct way of hiding visible elements when clicked anywhere on the page.

$(document).click(function (event) {            
    $('#myDIV:visible').hide();
});

The element (div, span, etc.) shouldn't disappear when a click event occurs within the boundaries of the element.


回答1:


If I understand, you want to hide a div when you click anywhere but the div, and if you do click while over the div, then it should NOT close. You can do that with this code:

$(document).click(function() {
    alert("me");
});
$(".myDiv").click(function(e) {
    e.stopPropagation(); // This is the preferred method.
    return false;        // This should not be used unless you do not want
                         // any click events registering inside the div
});

This binds the click to the entire page, but if you click on the div in question, it will cancel the click event.




回答2:


Try this

 $('.myDiv').click(function(e) { //button click class name is myDiv
  e.stopPropagation();
 })

 $(function(){
  $(document).click(function(){  
  $('.myDiv').hide(); //hide the button

  });
});

I use class name instead of ID, because in asp.net you have to worry about the extra stuff .net attaches to the id

EDIT- Since you added a another piece, it would work like this:

 $('.myDiv').click(function() { //button click class name is myDiv
  e.stopPropagation();
 })

 $(function(){
  $('.openDiv').click(function() {
  $('.myDiv').show(); 

  });
  $(document).click(function(){  
  $('.myDiv').hide(); //hide the button

  });
});



回答3:


As of jQuery 1.7 there's a new way to handle events. I thought I'd answer here just to demonstrate how I might go about doing this the "new" way. If you haven't, I recommend you read the jQuery docs for the "on" method.

var handler = function(event){
  // if the target is a descendent of container do nothing
  if($(event.target).is(".container, .container *")) return;

  // remove event handler from document
  $(document).off("click", handler);

  // dostuff
}

$(document).on("click", handler);

Here we're abusing jQuery's selectors and bubbling of events. Note that I make sure I clean the event handler up afterwards. You can automate this behaviour with $('.container').one (see: docs) but because we need to do conditionals within the handler that isn't applicable here.




回答4:


This following code example seems to work best for me. While you can use 'return false' that stops all handling of that event for the div or any of it's children. If you want to have controls on the pop-up div (a pop-up login form for example) you need to use event.stopPropogation().

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <a id="link" href="#">show box</a>
    <div id="box" style="background: #eee; display: none">
        <p>a paragraph of text</p>
        <input type="file"  />
    </div>

    <script src="jquery.js" type="text/javascript"></script>

    <script type="text/javascript">
        var box = $('#box');
        var link = $('#link');

        link.click(function() {
            box.show(); return false;
        });

        $(document).click(function() {
            box.hide();
        });

        box.click(function(e) {
            e.stopPropagation();
        });

    </script>
</body>
</html>



回答5:


Thanks, Thomas. I'm new to JS and I've been looking crazy for a solution to my problem. Yours helped.

I've used jquery to make a Login-box that slides down. For best user experience I desided to make the box disappear when user clicks somewhere but the box. I'm a little bit embarrassed over using about four hours fixing this. But hey, I'm new to JS.

Maybe my code can help someone out:

<body>
<button class="login">Logg inn</button>
<script type="text/javascript">

    $("button.login").click(function () {
        if ($("div#box:first").is(":hidden")) {
                $("div#box").slideDown("slow");} 
            else {
                $("div#box").slideUp("slow");
                }
    });
    </script>
<div id="box">Lots of login content</div>

<script type="text/javascript">
    var box = $('#box');
    var login = $('.login');

    login.click(function() {
        box.show(); return false;
    });

    $(document).click(function() {
        box.hide();
    });

    box.click(function(e) {
        e.stopPropagation();
    });

</script>

</body>



回答6:


What you can also do is:

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

  var container = $("div");

   if (!container.is(e.target) && container.has(e.target).length === 0)
  {
 container.fadeOut('slow');

   }

});

If your target is not a div then hide the div by checking its length is equal to zero.




回答7:


I did the below. Thought of sharing so someone else could also benefit.

$("div#newButtonDiv").click(function(){
    $(this).find("ul.sub-menu").css({"display":"block"});

    $(this).click(function(event){
        event.stopPropagation();
        $("html").click(function(){
            $(this).find("ul.sub-menu").css({"display":"none"});
        }
    });
});

Let me know if I can help someone on this.




回答8:


Try this:

 $(document).mouseup(function (e) {
    var div = $("#yourdivid");
    if (!div.is(e.target) && div.has(e.target).length === 0) 
    {
       div.hide();
     }
    });



回答9:


Another way of hiding the container div when a click happens in a not children element;

$(document).on('click', function(e) {
    if(!$.contains($('.yourContainer').get(0), e.target)) {
        $('.yourContainer').hide();
    }
});



回答10:


  $(document).on('click', function(e) { // Hides the div by clicking any where in the screen
        if ( $(e.target).closest('#suggest_input').length ) {
            $(".suggest_div").show();
        }else if ( ! $(e.target).closest('.suggest_container').length ) {
            $('.suggest_div').hide();
        }
    });

Here #suggest_input in is the name of textbox and .suggest_container is the ul class name and .suggest_div is the main div element for my auto-suggest.

this code is for hiding the div elements by clicking any where in the screen. Before doing every thing please understand the code and copy it...




回答11:


Try this, it's working perfect for me.

$(document).mouseup(function (e)
{
    var searchcontainer = $("#search_container");

    if (!searchcontainer.is(e.target) // if the target of the click isn't the container...
        && searchcontainer.has(e.target).length === 0) // ... nor a descendant of the container
    {
        searchcontainer.hide();
    }
});



回答12:


$('html').click(function() {
//Hide the menus if it is visible
});

$('#menu_container').click(function(event){
    event.stopPropagation();
});

but you need to keep in mind these things as well. http://css-tricks.com/dangers-stopping-event-propagation/




回答13:


Here is a working CSS/small JS solution based on the answer of Sandeep Pal:

$(document).click(function (e)
{
  if (!$("#noticeMenu").is(e.target) && $("#noticeMenu").has(e.target).length == 0)
  {
   $("#menu-toggle3").prop('checked', false);
  }
});

Try it out by clicking the checkbox and then outside of the menu:

https://jsfiddle.net/qo90txr8/




回答14:


This doesn't work - it hides the .myDIV when you click inside of it.

$('.openDiv').click(function(e) {
$('.myDiv').show(); 
e.stopPropagation();
})

$(document).click(function(){  
$('.myDiv').hide(); 

});

});

<a class="openDiv">DISPLAY DIV</a>

<div class="myDiv">HIDE DIV</div>



回答15:


Just 2 small improvements to the above suggestions:

  • unbind the document.click when done
  • stop propagation on the event that triggered this, assuming its a click

    jQuery(thelink).click(function(e){
        jQuery(thepop).show();
    
        // bind the hide controls
        var jpop=jQuery(thepop);
        jQuery(document).bind("click.hidethepop", function() {
                jpop.hide();
                // unbind the hide controls
                jQuery(document).unbind("click.hidethepop");
        });
        // dont close thepop when you click on thepop
        jQuery(thepop).click(function(e) {
            e.stopPropagation();
        });
        // and dont close thepop now 
        e.stopPropagation();
    });
    



回答16:


$(document).ready(function(){

$("button").click(function(){
   
       
        $(".div3").toggle(1000);
    });
   $("body").click(function(event) {
   if($(event.target).attr('class') != '1' && $(event.target).attr('class') != 'div3'){
       $(".div3").hide(1000);}
    }); 
   
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<button class="1">Click to fade in boxes</button><br><br>

<body style="width:100%;height:200px;background-color:pink;">
<div class="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div><body>



回答17:


$( "element" ).focusout(function() {
    //your code on element
})



回答18:


$(document).mouseup(function (e)
{
    var mydiv = $('div#mydiv');
    if (!mydiv.is(e.target) && mydiv.has(e.target).length === 0){
       search.slideUp();
    }
});



回答19:


Simple Solution: hide an element on a click event anywhere outside of some specific element.

$(document).on('click', function () {
                $('.element').hide();
            });
            //element will not Hide on click some specific control inside document
            $('.control-1').on('click', function (e) {
                e.stopPropagation();
            });


来源:https://stackoverflow.com/questions/714471/how-do-i-hide-an-element-on-a-click-event-anywhere-outside-of-the-element

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