CSS hover vs. JavaScript mouseover

Viewed 251356

There are times when I have a choice between using a CSS element:hover or JavaScript onmouseover to control the appearance of html elements on a page. Consider the following scenario where a div wraps an input

<div>
<input id="input">
</div>

I want the input to change background color when the mouse cursor hovers over the div. The CSS approach is

<style>
  input {background-color:White;}
  div:hover input {background-color:Blue;}
</style>

<div><input></div>

The JavaScript approach is

<div onmouseover="document.getElementById('input').style.backgroundColor='Blue';">
  <input id="input">
</div>

What are the advantages and disadvantages of each approach? Does the CSS approach work well with most web browsers? Is JavaScript slower than css?

11 Answers

The problem with :hover is that IE6 only supports it on links. I use jQuery for this kind of thing these days:

$("div input").hover(function() {
  $(this).addClass("blue");
}, function() {
  $(this).removeClass("blue");
});

Makes things a lot easier. That'll work in IE6, FF, Chrome and Safari.

The CSS one is much more maintainable and readable.

There is another difference to keep in mind between the two. With CSS, the :hover state is always deactivated when the mouse moves off an element. However, with JavaScript, the onmouseout event is not fired when the mouse moves off the element onto browser chrome rather than onto the rest of the page.

This happens more often than you might think, especially when you're making a navbar at the top of your page with custom hover states.

EDIT: This answer no longer holds true. CSS is well supportedand Javascript (read: JScript) is now pretty much required for any web experience, and few folks disable javascript.

The original answer, as my opinion in 2009.

Off the top of my head:

With CSS, you may have issues with browser support.

With JScript, people can disable jscript (thats what I do).

I believe the preferred method is to do content in HTML, Layout with CSS, and anything dynamic in JScript. So in this instance, you would probably want to take the CSS approach.

Use CSS, it makes for much easier management of the style itself.

In reguards to using jQuery to do hover, I always use the plugin HoverIntent as it doesn't fire the event until you pause over an element for brief period of time... this stops firing off lots of mouse over events if you accidentally run the mouse over them or simply whilst choosing an option.

If you don't need 100% support for IE6 with javascript disabled you could use something like ie7-js with IE conditional comments. Then you just use css rules to apply hover effects. I don't know exactly how it works but it uses javascript to make a lot of css rules work that don't normally in IE7 and 8.

Related