When you click Press Me
, a drop-down menu opens, and when you click it again or anywhere else in the window, it closes.
I also want to add this function to dropdown-arrow
next to it, so that it is synchronized.
I tried to give dropdown-arrow
onclick="myFunction()"
aswell, but it didn’t work.
function myFunction() {
document.getElementsByClassName('dropdown-content')[0].classList.toggle('show');
}
// Close dropdown if the user clicks on window
window.onclick = function(event) {
if (!event.target.matches('#verify-name')) {
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');
}
}
}
}
.buttons {
display: flex;
position: relative;
}
#dropdown-arrow {
height: 20px;
}
.dropdown-content {
display: none;
position: absolute;
padding: 14px; background-color: yellow;
}
.show {
display: flex;
}
<div class="buttons">
<div>
<a id="verify-name" onclick="myFunction()">Press Me</a>
<img id="dropdown-arrow" src="https://www.svgrepo.com/show/335062/dropdown.svg">
<div class="dropdown-content">
<span>Logout</span>
</div>
</div>
</div>
2
Answers
Add the onclick event to the dropdown-arrow in your HTML:
Modify the window.onclick function to check for both verify-name and dropdown-arrow:
With these changes, clicking either the "Press Me" link or the dropdown arrow will toggle the dropdown menu. Clicking anywhere else on the window will close it if it’s open.
I can think of 2 ways to tackle your issue:
closest
method to check if the clicked element isPress Me
text or the.dropdown-arrow
.Let me add the implementation of the second one. First one would be self-explanatory. In below code, I have replaced the
window.onclick
assignment withwindow.addEventListener('click', function() {...})
to avoid potential conflicts with other click event listeners and it is also the recommended way.