Ramez GaIal Ramez GaIal - 3 years ago 197
HTML Question

how to close an element when click outside?

when i click on the button, the button toggle a specific class and opens something, this works,
but the problem when i tried to type a code that will close that object when i click outside it, it doesn't work



$(function() {
$('button').on('click', function() {
$('.list').toggle();
$('button').toggleClass('something');
});
$(document).on('click', function(e) {
if (e.target !== 'list, button') {
$('.list').hide();
}
});
});

.list {
width: 100px;
height: 150px;
background: lightgray;
display: none;
}

button {
background: green
}

.something {
background: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='list'></div>
<button>button</button>




Answer Source

Try this code , here you will open the list and move over it but when you click outside of button and list , the list will be hidden :

var change ="y";

$('button').on('click', function() {
   if(change == "y") { $(".list").show(); }});

$('button').on('blur', function() {
    if(change == "x") { $(".list").hide();
    change="y";}});
  
      
$('.list').on('mouseover', function() { change="y";});
$('.list').on('mouseout', function() {change="x";
$('button').focus();});
          
.list {
  width: 100px;
  height: 150px;
  background: lightgray;
  display: none;
}

button {
  background: green
}

.something {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class='list'></div>
<button>button</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download