Skip to content Skip to sidebar Skip to footer

How To Close This Menu Clicking Outside?

I have this menu: CSS #message { display: none; position: absolute; width: 120px; background: #fff; color: #000; font-weight: bold; } When I click in it opens #messa

Solution 1:

You can bind a click handler to the document to close it:

Example: https://jsfiddle.net/jmpf1usu/4/

  $("#subm").click(function(evt) {
    $("#message").css({
      top: 55,
      left: evt.pageX + 55
    }).show();

      evt.stopPropagation();
  });

  $(document).click(function(){
      $("#message").hide();
  });

evt.stopPropagation()is required so that the click never reaches the document, thus immediately triggering it to close again.


Solution 2:

Try changing your js to this:

$("#subm").click(function() {
  $("#message").show();
 });

$("#message").mouseleave(function(){
   $("#message").hide(); 
});

When the user hits the button the menu will open. When the user mouse leaves the div it will hide it. Is that what you're looking for?

If you really want a click to remove the visibility you can do:

$("body").on('click',function(){
   $("#message").hide(); 
});

I just prefer the mouse leave, tbh.


Solution 3:

You can use the below code for hide message

$(function() {
	

	
  $("#subm").click(function(evt) {
      
    $("#message").css({
	  top: 55,
      left: evt.pageX + 55
    }).show();
  });
    $(document).click(function(event) {
    if (!$(event.target).is("#subm")) {
        $("#message").hide();
    }
  });
  
});
    #message { 
     display: none; 
     position: absolute; 
     width: 120px; 
     background: red; 
     color: #fff; 
     font-weight: bold; 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="subm">open</span>

<div id="message">
message
</div>

Solution 4:

please try with below code snippet.

$(function() { 
  $("#subm").click(function(evt) {
       evt.stopPropagation();
    $("#message").css({
      top: 55,
      left: evt.pageX + 55
    }).show();
  });


    $('html').click(function() {
        $("#message").hide();
    });
});

JSFiddle


Solution 5:

Try this:

$(function () {    
    $("#message").click(function (evt) {
        evt.stopPropagation();
    });
                     
    $("#subm").click(function (evt) {
        evt.stopPropagation();
        $("#message").css({
            top: 55,
            left: evt.pageX + 55
        }).toggle();
    });

    $('html').click(function (evt) {
        if ($('#message').is(":visible")) {
            $('#message').hide();
        }
    });
});
#message {
    display: none;
    position: absolute;
    width: 120px;
    background: red;
    color: #fff;
    font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="subm">open</span>
<div id="message">message</div>

Post a Comment for "How To Close This Menu Clicking Outside?"