0

I am looking at the first dropdown button example on this W3schools page and it seems I cannot figure out which part of the JavaScript is responsible for hiding the menu when you click outside of the dropdown menu boxes.

  /* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the Traveled Distance dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
    for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('show')) {
            openDropdown.classList.remove('show');
      }
    }
  }
}
/* Dropdown Button */
.dropbtn {
  background-color: #3498DB;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
  background-color: #2980B9;
}

/* The container <div> - needed to position the dropdown content */
.dropdown {
  position: relative;
  display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

/* Links inside the dropdown */
.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #ddd}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}
<div class="dropdown">
  <button onclick="myFunction()" class="dropbtn">Dropdown</button>
  <div id="myDropdown" class="dropdown-content">
    <a href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#contact">Contact</a>
  </div>
</div>

I know W3schools has pretty accurate descriptions, this one however, does not shed enough light for me on how the JS works in this particular case.

I am glad to hear any additional explanations and translations into pseudo code. Thank you!

P.S: I am asking because I am replicating it to be used several times within a page and on one of the occasions it fails to hide the menu when you click outside, while it is identical as a structure with only the classes and IDs changed respectively.

Moreover, the main source of confusion for me is this part of the snippet:

        if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
        }

What kind of object is 'show' in this context? Is it just a string? Is it a class added to some of the elements? If not, what it is?

And here are also all the contents of my JavaScript file that fails on myFunction() but works as I expect it on showCountries() with another dropdown I have nested in my page, identical to the working one but with the respective IDs and classes named differently as addressed within my JS:

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the Traveled Distance dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
    for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('show')) {
            openDropdown.classList.remove('show');
      }
    }
  }
}

/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function showCountries() {
    document.getElementById("myDropdownCountry").classList.toggle("show");
}
  
// Close the Country dropdown menu if the user clicks outside of it
window.onclick = function(event) {
    if (!event.target.matches('.dropbtnCountry')) {
        var dropdowns = document.getElementsByClassName("dropdown-contentCountry");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
                var openDropdown = dropdowns[i];
                if (openDropdown.classList.contains('show')) {
                openDropdown.classList.remove('show');
            }
      }
    }
}

function writeCountryContents(countryChoice) {
//  de.onclick = outputChoice() {
        document.getElementById('buttonContent').innerHTML = countryChoice;
//  }
}

function writeTravelContents(dropDownChoice) {
//  de.onclick = outputChoice() {
        document.getElementById('traveledDistance').innerHTML = dropDownChoice;
//  }
}

Here is also a comparison of the two dropdowns separated into two files (I originally had them in one file), apart from a few spaces and renamed functions, there is no other difference I am able to spot so that I could make it work: enter image description here

apingaway
  • 33
  • 1
  • 1
  • 17
  • Does this answer your question? [Create dropdown menu on click and close menu when clicked outside with Vanilla Javascript](https://stackoverflow.com/questions/67041940/create-dropdown-menu-on-click-and-close-menu-when-clicked-outside-with-vanilla-j) – Dimitar Jun 06 '22 at 14:07
  • Sorry, nope. :( – apingaway Jun 06 '22 at 14:28

1 Answers1

1
window.onclick = function(event) { // add event listener on window
  if (!event.target.matches('.dropbtn')) { // check whether click was made outside of dropdown
    var dropdowns = document.getElementsByClassName("dropdown-content"); // find all elements with class dropdown-content
    var i;
    for (i = 0; i < dropdowns.length; i++) { // iterate through all dropdowns
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) { // check whether it has class 'show'
        openDropdown.classList.remove('show'); // remove class 'show'
      }
    }
  }
}

you have click listener on window. It fires when you click outside of dropdown and calls openDropdown.classList.remove('show');

drent
  • 104
  • 8
  • 1
    It fires when you click _anywhere_ but only removes class `show` from all dropdowns when the click event does not come from a target with class `dropbtn`. – Sergiu Paraschiv Jun 06 '22 at 14:07
  • Hi! @drent228 Okay, that helps me understand another chunk of it. Nevertheless, I still cannot get it to work with my original myFunction() that I just copied and pasted but I made it work in an unknown to me way with showCountries() (another identical dropdown). I have edited my original post and at the end of it you can see my entire JS file. What seems to be wrong in your opinion? – apingaway Jun 06 '22 at 14:13