By clicking on the button labeled Press Me
, you can open a drop-down menu. Clicking on it again or anywhere in the window will close the menu.
I want to synchronize this function with the dropdown-arrow
located next to it as well.
I attempted to give the dropdown-arrow
the attribute onclick="myFunction()"
, however, it did not have the desired effect.
function myFunction() {
document.getElementsByClassName('dropdown-content')[0].classList.toggle('show');
}
// If user clicks outside the dropdown, close it
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>