I recently found myself needing to design a vertical menu that makes uses of the CSS :hover selector.
In this particular case I also wanted the last item that was in a hover state to stay in that state. In other words: if I was half way down the menu with my mouse then moved it away, I wanted that item to stay changed until the mouse was returned to perhaps another item in the menu.
What I ended up with was a mix of CSS and Javascript (but mostly Javascript). Please note that I’m no Javascript expert, so there may very well be a better way to do this. Having said that, I’ve successfully tested this in IE8, Firefox 4 beta, Safari 5.
Edit: I’m aware that this could be done quite easily with jQuery but I wanted to have a go at doing it without using the library.
The Javascript placed between the head tags
<script type="text/javascript">
function trig(elid) {
//Change the bg image for element with the current mouseover
document.getElementById(elid).style.background = 'url(images/click.png) center left no-repeat';
//List of all the element ids (Perhaps this can be generated dynamically?)
var names = ["bb", "trc", "mb", "ch"];
//Need this because indexOf is incompatible with IE8
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] == obj) { return i; }
}
return -1;
}
}
//Find the index of the element currently triggered by the mouseover
var idx = names.indexOf(elid);
//Remove the element from the array
if(idx!=-1) names.splice(idx, 1);
//For each element still left in the array make sure it's got the default background
for (i=0;i<names.length;i++)
{
document.getElementById(names[i]).style.background = 'url(images/dot.png) center left no-repeat';
}
}
</script>
The HTML
<div id="locations_menu">
<ul>
<li class="first" id="bb"><a href="#" onmouseover="trig('bb')">MENU ITEM 1</a></li>
<li id="trc"><a href="#" onmouseover="trig('trc')">MENU ITEM 2</a></li>
<li id="mb"><a href="#" onmouseover="trig('mb')">MENU ITEM 3</a></li>
<li id="ch"><a href="#" onmouseover="trig('ch')">MENU ITEM 4</a></li>
</ul>
</div>
The end result with a bit of styling

CSS and Javascript hover with a memory
The live version
CSS and Javascript hover with a memory