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.