skip to Main Content

I was writing code for closing dropdown window outside of its scope. For that purpose I used simple if condition to check, whether click event’s id coincides with the id of dropdown button not every click should be considered to close menu). It was unexpected to see, that almost same condition statements are considered differently by vanilla JS.

To show the difference, I’ll provide here two code snippets:

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event){
    if (event.target.id == dropDownBtn.id){
        console.log("ok"); //  console output: ok
    }
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
    if (event.target.matches(dropDownBtn.id)){
        console.log("ok"); //  console output:
    }
}

Having zero to little experience in JS, I’d like to know why first snippet works well, whereas second not.

3

Answers


  1. To fix the second code snippet, you can modify the condition to use a valid CSS selector by prefixing the id with a # symbol, like this:

    window.onclick = function(event) {
        if (event.target.matches('#' + dropDownBtn.id)){
            console.log("ok"); // console output: ok
        }
    }
    Login or Signup to reply.
  2. You have an error in the matches example. You need the ‘#’ prefix:

    // Close the dropdown menu if the user clicks outside of it
    window.onclick = function(event) {
        if (event.target.matches('#' + dropDownBtn.id)){
            console.log("ok"); //  console output:
        }
    }
    

    Otherwise the 2 methods seems equal.

    BUT you have a problem with your approach.
    e.target could be any clicked element in the dropdown.

    So to solve that you need to check whether the clicked element is INSIDE your dropdown or your dropdown itself, also using document looks more idiomatic:

    document.addEventListener('click', e => {
      e.target.closest('#' + dropDownBtn.id)?.style.display = 'none';
    });
    
    
    Login or Signup to reply.
  3. event.target.matches(dropDownBtn.id) is using the matches method to check if the element that was clicked (event.target) matches the CSS selector provided (dropDownBtn.id).

    The matches method checks if the element itself or any of its ancestors match the selector. But, dropDownBtn.id only provides the id of the dropdown button element, which is not a valid CSS selector.
    Check this documentation for more info
    (https://developer.mozilla.org/en-US/docs/Web/API/Element/matches)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search