Weird button hitbox(click-area?)
Hello! I'm having problem with button click-area when using Event Delegation. Basically only a small part of button is respond to being clicked if button has content inside of it, but if I directly target it with EventListener it works fine. Why is that?
Picture below is example of a button, consisted of <img> and <p> tag. It only registers click when clicked between the "arrow" and "Reply" text when being targeted by EventDelegation, but works fine when you attach Listener to it.
Project link below if you want to test it. When you click in between arrow and text, in console "Not working" text will appear, when it should appear when clicked on the whole button.
Code being used to show that message, where "reply-btn" is class name of the whole button.
Button HTML
Project link: https://astonishing-cupcake-035f30.netlify.app/
18 Replies
Try using
event. currentTarget
. That will work as the event bubbles up the DOM tree.
event.target
is what is actually clicked on. So if you click on the image the event.target
will be the image. But if you use event. currentTarget
it’ll fire as the click event propagates upward.Like this:
?
Almost. Your console log statement is a bit off :p
It shoots me an an error
xD
Also, TIL that
.matches()
is a thing!
What’s the error?Just a sec
😄
Uncaught TypeError: event.currentTarget.matches is not a function
at HTMLDocument.<anonymous> (index.js:219:26)
🤔
Yeah for .matches(), it was in example of Event Delegation so I just pasted it into code xD
Apparently
.currentTarget
doesn’t return an Element
so it doesn’t have the .matches()
method
Best thing to do is log the current target and see what it shows. There will be a way to get the class listWait I'm confused to what I need to do?
maybe just use
contains?
You need to log the current target and see what methods and properties it has
How do I do that? 😄
If it does not work
With matches
Don’t try to match. Just
console.log(event.currentTarget)
And look at the logyeah but EventListenr is on the document
One of the items logged will be the weekend element
If I do not say that I'm targeting ('.reply-button')
it will return document
?
That is what is confusing me
Was on my phone, working from memory. Give me a sec to troubleshoot on my computer
Sure! 😄
Ok, got it:
https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
event.target.closest({CSS selector here})
is what I was missing
The closest()
method of the Element interface traverses the element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.
Oh
nice
😄
Thanks!
I'll try it
Yup!
Works! 😄
Thanks!