Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS hover vs. JavaScript mouseover [closed]

Tags:

javascript

css

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?

like image 535
John Avatar asked Mar 04 '09 00:03

John


Video Answer


2 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.

like image 178
cletus Avatar answered Sep 23 '22 03:09

cletus


The CSS one is much more maintainable and readable.

like image 21
Ólafur Waage Avatar answered Sep 23 '22 03:09

Ólafur Waage