<div>
<button id="button">Open Dropdown</button>
<ul id="dropdown" style="display:none; background:#f1f1f1">
Dropdown Body
</ul>
</div>
<script>
let open = false;
let dropdown = document.getElementById('dropdown');
let button = document.getElementById('button');
button.addEventListener('click', function(){
if(dropdown.style.display == 'none'){
dropdown.style.display = 'block';
open = true;
} else {
dropdown.style.display = 'none';
open = false;
}
});
document.body.addEventListener('click', function(e){
if(e.target.id != button.id && e.target.id != dropdown.id){
dropdown.style.display = 'none';
open = false;
}
});
</script>
html, body{
height:100%;
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.