2

The Following code adds an image before header tag. How can add javascript or jquery code for handling some task when the image added before the header was clicked.

h1::before 
{
    content: url(smiley.gif);
}

The Html code is :

 <html>
   <body>
     <h1>Hi </h1>
   </body>
 </html>

2 Answers 2

5

You cannot attach events on pseudo class elements since they are not part of the DOM, you can only attach events to the original elements or parents.

You can create an element containing the image and position it in the same place that the pseudo element is positioning it, and attach any event handler to it.

2
1

Pseudo elements such as :before and :after in CSS aren't part of the DOM and can't be altered or interacted with javascript. You would need to add the image to a 'real' element and attach the event handlers to that if you want it to be interacted with.

3
  • Thank you Sir for you answer,I will try
    – Venkat
    Oct 7, 2015 at 6:32
  • 1
    Seems like a bit of an oversight of the specification to be honest.. I've never much used the before or after pseudo-selectors, much less modified their contents, but it might be useful to have the ability to. Perhaps the ECMA Script 6 specs will define it.
    – brads3290
    Oct 7, 2015 at 7:01
  • It is possible by changing an attribute that would get picked up by one of your CSS-selectors and then modify it in that context. Pseudo elements as a part of the DOM is not in the ES6 spec and I don't think it is going to be since CSS uses its own object model (CSSOM)
    – Frinsh
    Oct 9, 2015 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.