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

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


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.


There is no :before and :after selector in jQuery. However as an alternative, you can check the location of the click event and check if it is on your pseudo-element:

(I haven't tested this)

style:

#mything {    width: 100px;    height: 100px;    position: relative;    background: blue;}#mything:after {    content: "x";    font-size: 10px;    position: absolute;    top: 0;    right: 0;    background: red;    width: 10px;    height: 10px;}

javascript:

$('#mything').click(function(e) {    if (e.clientX > $(this).offset().left + 90 &&        e.clientY < $(this).offset().top + 10) {        // do something    }});

html:

<div id="mything">Foo</div>