Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Oly Su
Oly Su
6,119 Points

How to use :hover efficiently? To javascript or no javascript?

Could anyone please kindly comment ways to use the pseudo-class :hover efficiently?

:hover is very commonly used but unfortunately it is the least efficient CSS selector.

Would using javascript with onmouseover (or jQuery .hover, if the jQuery library is being used) effects a more efficient option? Also in terms of ongoing management, is this more feasible with the javascript approach?

Things like :nth-child I would do it in the markup, but :hover is quite a tricky one.

Your thoughts?

Many thanks :)

2 Answers

Adam Moore
Adam Moore
21,956 Points

As far as I understand it, when using CSS, the browser doesn't have to spend as much time or "energy" loading Javascript, so it is more efficient to have the hover function in CSS than Javascript. Plus, if the user has Javascript disabled, I believe that CSS would still work, but if the mouseover function was used, the same effect wouldn't get executed. I'm not 100% sure, but I feel like this is something that I remember learning on here.

Adam Moore is correct. If it is possible to use CSS to perform the hover effect, first try that. If the interactivity you need goes beyond what CSS can do then that is where you may need to start looking into JavaScript.

Oly Su
Oly Su
6,119 Points

Thanks guys, that's very helpful :)