简体   繁体   中英

Make Dropdown menu Disappear

I have a code from W3schools, in which we get dropdown menu after clicked on a button.

Dropdown menu don't disappear when we click anywhere else. I have surfed a bit but it seems confusing as am new to js.

It would be much helpful if anyone could suggest how do we make it disappear?

Code Link

Add the following code somewhere:

document.getElementById("myBtn").onblur = function() {
  document.getElementById("myDropdown").classList.remove("show");
};

The original code that you wrote triggers the addition or removal of the "show" class on the element of id "myBtn" only when this element itself is clicked:

document.getElementById("myBtn").onclick = function() { document.getElementById("myDropdown").classList.toggle("show"); };

But it does nothing if you click outside, that's the role of the onblur event.

<script>
// Get the button, and when the user clicks on it, execute myFunction
document.getElementById("myBtn").onclick = function() {
  myFunction()
};
document.getElementById("myBtn").onblur = function() {
  myFunction();
};

/* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */
function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}
</script>

Use this:

 document.getElementById("myBtn").onblur = function(){ document.getElementById("myDropdown").classList.remove('show') }; 

"onBlur" is the Event for losing the focus

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM