porque_no_les_deux
porque_no_les_deux

Reputation: 479

What happens first, CSS or JS events?

If, for example, you put a CSS hover effect on an element, and also put a JS mouseenter event on it, which one will happen first? Is there any variance with this? Can you control it somehow? Is it possible to force them to execute in a particular order?

Upvotes: 4

Views: 331

Answers (2)

Bergi
Bergi

Reputation: 664503

which one will happen first?

Notice that there is no such thing as a "CSS event". However, the behaviour is undefined; you could consider the CSS change and the JS event to happen at the same time. The relevant specs CSS Selectors 4, DOM 3 Events and HTML 5 point out the similarities between hover and mouseenter, but do not specify an order. Mouse event order is specified, but does not refer to CSS user action pseudo classes.

Is there any variance with this?

Yes, browsers are free to implement it either way. They could change the layout and redraw the page before they fire the JS events, or they could not. It should however not make much difference.

Is it possible to force them to execute in a particular order?

I personally would expect in the CSS to be applied already when the JS event handler is executed. Even if it was not yet computed, when querying styles (e.g. getComputedStyle(this)) a CSS recomputation is done so that you should always get the dynamic styles - see also When does reflow happen in a DOM environment?.

Try it out at http://jsfiddle.net/n4Z8H/. While most major browsers will yield the expected value (rgb(0, 0, 255), the blue :hover style), older IEs don't seem to do.

Upvotes: 3

Zoey Mertes
Zoey Mertes

Reputation: 3144

Depends a lot on how the browser works, and shouldn't be relied on. Most browsers should run the two at almost exactly the same time. If you want one to execute before/after the other, just control the CSS styling via JavaScript, for example on hover add a class and on not hover remove the class.

Although, if this is an actual issue you have, you're probably doing something wrong.

Upvotes: 0

Related Questions