I have a div
element with a CSS pseudo-element ::before
used as a close button (instead of using an actual button). How do I apply an event listener to only the pseudo-element?
HTML
<div id="box"></div>
CSS
#box:before { background-image: url(close.png); content: ''; display: block; height: 20px; position: absolute; top: -10px; right: -10px; width: 20px; } #box { height: 100px; width: 100px; }
Special welcome offer: get $100 of free credit. CSS ::before and ::after pseudo-elements allow you to insert “content” before and after any non-replaced element (e.g. they work on a <div> but not an <input> ). This effectively allows you to show something on a web page that might not be present in the HTML content.
::after (:after) In CSS, ::after creates a pseudo-element that is the last child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.
Your answer If you must have a click handler on the red region only, you have to make a child element, like a span, place it right after the opening <p> tag, apply styles to p span instead of p:before, and bind to it.
Was looking for a solution and found this thread. Now want to share my workaround:
CSS
element { pointer-events: none; } element::after { pointer-events: all; }
JS
element.addEventListener('click', function() { ... });
This works if you don't need any pointer events on element
. Check it in action.
No. The pseudo-element does not exist in the DOM so it has no HTMLElementNode
object representing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With