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

霸气de小男生 提交于 2019-11-27 21:02:37
Quentin

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

Was looking for a solution and found this thread. Now want to share my solution:

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.

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>
Yuri Sulyma

If the position and dimensions of the generated content are known, you can add a click handler on the element itself and check the relative mouse position before handling it.

This is perverse, but possible.

Generally speaking no as indicated by others. But in case your tag with pseudo-element is empty, such as glyphicon in bootstrap.

You can wrap a div or span or whatever tag suitable in your case. Glyphicons in bootstrap uses :before but on the page you can see that it has hover event caught.

Example:

<span>
  <span class="glyphicon glyphicon-asterisk" aria-hidden="true"></span>
</span>

Suppose you want to add event to the above glyphicon, you can use jquery parent selector

$('glyphicon').parent('span').click(function() { 
  // awesome things
});

Just a small trick in case your tag is empty.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!