Hover Effects in JavaScript?

One of the things that can be annoying when looking at someone else’s code is when a more complex technology is used to solve a problem that can be handled more simply with another method.

An example of this is when you utilize JavaScript to implement a hover effect on some elements. I know of one scenario when you would need JavaScript to trigger a hover effect, and that would be when you want to trigger the hover effect with a touch event. However, in this case, the elements that would be affected by this hover effect are hidden on any mobile device, so the touch events would be unneeded for this hover effect.

The solution? It is to utilize the :hover pseudo-class in the CSS selector and style the elements appropriately instead of adding and removing hover-specific classes. Much simpler, more elegant, and it has been the best-practice for years.

comments powered by Disqus

Related Posts

JavaScript Templating

Many times it becomes useful to be able to make an AJAX request for some data, insert it into some HTML that is already on the client, and then display it to the user. There are a few ways to implement this, each approach has its benefits and drawbacks. String Concatenation Possibly the simplest way to accomplish the templating in JavaScript is to use simple string concatenation with ‘+’. This is the approach that I see many newcomers to JavaScript use in their code, as it is the simplest to implement.

Read More