Forum Moderators: open
<ul>
<li>1</li>
<li>2</li>
<li>3
<ul>
<li>3.1</li>
<li>3.2</li>
<li>3.3</li>
</ul>
</li>
</ul> li { background: #fff; }
li:hover { background: #ccc; } This works fine, up until you hover over the sublist. You then get a grey background on both the <li> you're hovering over and the parent <li>. What I want is just the <li> at the 'front' to be highlighted.
I've tried to rework this in JS but I'm really not having much luck. I think I need the standards-equivalent of IE's onmouseenter and onmouseleave. I suppose I could do something with cancelling the event bubbling to fix this but it's at this point that my understanding gets a little hazy.
Help?
li { background: #fff; }
li a:hover { background: #ccc; display:block; }
<ul>
<li><a href="">1</a></li>
<li><a href="">2</a></li>
<li><a href="">3</a>
<ul>
<li><a href="">3.1</a></li>
<li><a href="">3.2</a></li>
<li><a href="">3.3</a></li>
</ul>
</li>
</ul>
For you second option, being invalid isn't really an option for this project. The <a> trick would be useful, but actually the HTML inside each list item is a little more complex - too complex to nest everything inside an inline <a> (again, this would make it invalid).
The reason why I suggested it was a bubbling issue wasn't the CSS but more the JS equivalent I'd built. This behaves in the same way as :hover in that the mouseover event bubbles up through the <li>s and sets the background colour on each.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset:utf-8">
<title></title>
<style type="text/css">
.hovered {
background: #eee;
}
</style>
</head>
<body>
<ul id="myList">
<li>1</li>
<li>2</li>
<li>3
<ul>
<li>3.1</li>
<li>3.2</li>
<li>3.3</li>
</ul>
</li>
</ul>
<script type="text/javascript" src="http://yui.yahooapis.com/2.3.1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript">
YAHOO.util.Event.on(window, 'load', function() {
// Attach mouseover and mouseout event listeners
var myList = document.getElementById('myList');
var liList = myList.getElementsByTagName('li');
YAHOO.util.Event.on(liList, 'mouseover', function(e) {
YAHOO.util.Event.stopEvent(e);
YAHOO.util.Dom.addClass(this, 'hovered');
});
YAHOO.util.Event.on(liList, 'mouseout', function(e) {
YAHOO.util.Dom.removeClass(this, 'hovered');
});
});
</script>
</body>
</html>
Hope that helps.