I have a button in my HTML Tailwindcss page like so:
<div >
<button
id="button-fab-anchor"
>
<span >
<i id="up-icon" ></i>
<i id="down-icon" ></i>
</span>
</button>
<ul id="button-fab-list" >
<li> Buttons here... </li>
</ul>
</div>
On the page I have the following JS:
document.addEventListener("DOMContentLoaded", function(event) {
const btnAnchor = document.getElementById('button-fab-anchor');
if (btnAnchor) {
const btnList = document.getElementById("button-fab-list");
const upIcon = document.getElementById("up-icon");
const downIcon = document.getElementById("down-icon");
btnAnchor.addEventListener("click", function(event) {
if (event.target == btnAnchor) {
btnList.classList.toggle('hidden');
upIcon.classList.toggle('hidden');
downIcon.classList.toggle('hidden');
}
});
}
});
This works fine if I click on the button but not on the icon in the button. I have tried using z-index to place the button parent at z-50 and the icon as z-10 so the parent is stacked above the child.
What sis I miss / How do I set up the event to work on the button parent and all its children (i.e.: the icon)?
CodePudding user response:
Use pointer-events: none; for the span inside the button.
Since it's tailwindcss (use: pointer-events-none on the span) you have:
<button id="button-fab-anchor" >
<span >
<i id="up-icon" ></i>
<i id="down-icon" ></i>
</span>
</button>
CodePudding user response:
Inside your addEventListener, you have an if condition that checks if the target is btnAnchor (i.e. #button-fab-anchor) or not. So the if condition won't be true if the event target is the icon.
btnAnchor.addEventListener("click", function(event) {
if (event.target == btnAnchor) {
btnList.classList.toggle('hidden');
upIcon.classList.toggle('hidden');
downIcon.classList.toggle('hidden');
}else{
//CLicked on something else.
}
});
CodePudding user response:
In your code, the if condition is if (event.target == btnAnchor).
The target object is icon not button when you click the icon, so js core neither enter the block, nor execute this action:
btnList.classList.toggle('hidden');
upIcon.classList.toggle('hidden');
downIcon.classList.toggle('hidden');
