JavaScript/CSS: imitate hover

hankknight
hankknight used Ask the Experts™
on
I would like to initiate the CSS :hover effect using JavaScript.

So when a user clicks on "Active CSS Hover Effect for item 1" the whatever the stylesheet says has set for li:hover for that item should apply.
<html> 
<head> 
<title>Test</title> 
<script type="text/javascript"> 
</script> 

<style type="text/css">

li:hover {
background: red;
}

</style>

</head> 
<body> 
 
<h1>Hello</h1>

<ul>
<li id="foo1">One</li>
<li id="foo2">Two</li>
<li id="foo3">Three</li>
</ul>	


<hr />

<input type="button" value="Active CSS Hover Effect for item 1" onclick="itemHover('foo1');" />
<input type="button" value="Active CSS Hover Effect for item 2" onclick="itemHover('foo2');" />
<input type="button" value="Active CSS Hover Effect for item 3" onclick="itemHover('foo3');" />
 
</body> 
</html>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
i think the better solution is setting the class:

li.hover {
  background: red;
}


<script type="text/javascript">
   function itemHover(elm)
   {
     document.getElementById(elm).className = 'hover';
   }
</script>

Author

Commented:
Is my idea possible?
i think yes, but it's more complicated, and it needs a bunch of JS code to parse the document's style sheet

there are some scc parsers, like this one: http://www.senocular.com/index.php?id=1.289, or jquery

anyway, i recommend you to use my solution, if you don't have any other special reason

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial