Issue
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>
Solution
I can think of 2 ways to tackle your issue:
- Attaching a separate click event listener for the dropdown-arrow.
- Using the
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 with window.addEventListener('click', function() {...})
to avoid potential conflicts with other click event listeners and it is also the recommended way.
function toggleDropdown() {
document.querySelector('.dropdown-content').classList.toggle('show');
}
window.addEventListener('click', function(event) {
const clickedElement = event.target;
if (clickedElement.closest('#verify-name') || clickedElement.closest('#dropdown-arrow')) {
// Clicked on "Press Me" or the dropdown-arrow
toggleDropdown();
} else {
// Clicked outside the dropdown elements
document.querySelectorAll('.dropdown-content.show').forEach(function(openDropdown) {
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">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>
Answered By - mandy8055
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.