Reputation: 5
I have a icon in a button. When I click the button (literally rest of the area of the button except the icon), the button will show a drop down list under it. However, when I click the down arrow icon in the button, the drop down list doesn't show up. I need to make sure both button and icon are clickable. How do I do that?
Here is the code snippet:
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
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');
}
}
}
}
#myDropdown {
display: none;
}
#myDropdown.show {
display: block;
}
<div class="dropdown">
<button onclick="myFunction()" class="btn dropbtn btn-primary">
More <i style='font-size:16px' title='More' class='fas'></i>
</button>
<div id="myDropdown" class="dropdown-content" style="line-height:15px;">
<a href="#" target="_blank">Duplicate New</a>
<a href="#" target="_blank">Download PDF</a>
<a href="#" target="_blank">Print PDF</a>
<a href="#" class="delete" data-id="{{ $dataTypeContent->getKey() }}" id="delete-{{ $dataTypeContent->getKey() }}">Delete</a>
</div>
</div>
Upvotes: 0
Views: 375
Reputation: 11
The window.onclick
function should also be triggered when you click either on the <button>
or <i>
, but since the event.target
is not dropbtn
when you click on the <i>
it's most likely passing the if (!event.target.matches('.dropbtn'))
check and closing the dropdown like it would if you clicked elsewhere on the screen.
I'd try if (!event.target.matches('.dropbtn') && !event.target.matches('.fas'))
to see if that fixes it. If so, I'd add a more specific class to the <i>
such as dropdown-toggle
and check if it matches that, otherwise it wouldn't close the dropdown if you click any other font-awesome icon on the screen.
Update - looks like that did it, here is the JSFiddle https://jsfiddle.net/p1kw746q/
Upvotes: 1