Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event listener on a CSS pseudo-element, such as ::after and ::before?

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; } 
like image 582
jenswirf Avatar asked Feb 22 '12 13:02

jenswirf


People also ask

When would you use the :: before or :: after pseudo-element in your CSS?

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.

What is :: after in CSS?

::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.

How can I only detect click event on pseudo-element?

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.


2 Answers

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.

like image 184
p.boiko Avatar answered Oct 14 '22 09:10

p.boiko


No. The pseudo-element does not exist in the DOM so it has no HTMLElementNode object representing it.

like image 33
Quentin Avatar answered Oct 14 '22 08:10

Quentin