Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to detect a click of an :after or :before pseudo element with jQuery? [duplicate]

Tags:

jquery

css

Lets say I have:

<div></div>

with:

div {
    width: 500px;
    height: 500px;
    position: relative;
}
div:after {
    content: '';
    display: block;
    width: 20px;
    height: 20px;
    position: absolute;
    top: 0;
    right: 0;
}

Can I do something like $('div:after').click(function(){...}); ? And have it not fire if I am clicking on div but not div:after.

like image 967
dezman Avatar asked Mar 29 '13 16:03

dezman


People also ask

How does pseudo-element detect click?

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. Hope it helps!!

What do the pseudo selectors before and after allow you to do?

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.

Which pseudo class detects whether the user has clicked on an element called Help?

User action pseudo-classes Matches when an item is being activated by the user. For example, when the item is clicked on. Matches when an element has focus.

How do I target a pseudo-element in JavaScript?

You can't select pseudo elements in jQuery because they are not part of DOM. But you can add a specific class to the parent element and control its pseudo elements in CSS. Show activity on this post. We can also rely on custom properties (aka CSS variables) in order to manipulate pseudo-element.


1 Answers

Maybe. Depending on how you structure your pseudo content you would have to rely on calculating mouse position for clicks on the actual div. The event handlers would all go on the div, and not the pseudo element because it doesn't exist in the DOM.

See Manipulating CSS :before and :after pseudo-elements using jQuery for some more info. Especially BoltClock's answer.

Also see Felix's comment for another possible solution without mouse position: Only detect click event on pseudo-element

like image 68
ryan Avatar answered Oct 06 '22 23:10

ryan