Search code examples
jquerycssjquery-animatepseudo-class

How to animate or timing a Pseudo class using jQuery


Say I have an element and I want to change it on a hover state.

Using a Pseudo class it will look like this:

#element:before { background-position: 0px -50px; }
#element:hover:before { background-position: -50px -50px; }

Can I implement a jQuery animation function to it? or can I time its transition?


Solution

  • This is not possible with jQuery.

    Content created by :after or :before is not part of the DOM and therefore cannot be selected or modified.
    - (source)

    You could use this in your CSS to achive a transition effect, but this will not work in older browsers:

    #element:before {
        -webkit-transition: background-position 1s linear;
        -moz-transition: background-position 1s linear;
        -o-transition: background-position 1s linear;
        -ms-transition: background-position 1s linear;
        transition: background-position 1s linear;
    }