I’m working on claculator and one of the buttons doesnt responds as rest. First click on it doesnt log to the console. After I click a button for root and then go to square it starts to work. I notice that whe i remove tag then it is working normally
<button class="btn instant-operator btn--squere" data-tab="x2">
<i>x<sup>2</sup></i>
</button>
<button class="btn instant-operator btn--root" data-tab="root">
√x
</button>
Some JS code:
function instantOperator(iOperator) {
console.log(iOperator);
}
const actionBtn = function (e) {
const clicked = e.target;
clicked.classList.remove("btn--clicked");
void clicked.offsetWidth; // trigger reflow
clicked.classList.add("btn--clicked");
if (clicked.classList.contains("integer")) {
integer(clicked);
} else if (clicked.classList.contains("operator")) {
operator(clicked);
} else if (clicked.classList.contains("instant-operator"))
instantOperator(clicked);
};
btnsBody.addEventListener("click", actionBtn);
2
Answers
The
event.target
is normally the element the user clicked on. If you click on the text inside a nested node, theevent.target
will be the respective node.From MDN:
You can avoid this, by looking at the event path using event.composedPath():
By using css
pointer-events: none;
for all child elements of a button:Or by using the
event.currentTarget
orthis
inside normal functions.use e.currentTarget
target returns clicked element
currentTarget returns your event binded element
look below