Posts Tagged ‘code’

Simple Way to Modify Menu Items with jQuery

// September 16th, 2008 // No Comments » // javascript, tech

I came across this website the other day using some really ingenious css that would change the state of a menu item as you hover over it with the mouse, while also changing the states of all other items in the menu that are not hovered. Pretty interesting. I’ve been so hooked on jQuery lately that I was curious to see if I could throw something together quickly that accomplished the same feat. It was actually a lot easier than I thought it would be.

$(function(){
$("#menu li").hover(function() {
$(this).addClass("hover");
$("#menu li").not(".hover").addClass("nothover");
},function(){
$(this).removeClass("hover");
$("#menu li").not(".hover").removeClass("nothover");
});
});

Basically, I made it so that when the list item “li” contained in the “#menu” container is hovered over with the mouse, a class of “hover” is added to that item, while every list item not hovered in that set gets a class of “nothover”. Now, once the user’s mouse exits the list item, it removes both the “hover” and “nothover” classes. Simple, eh?

From here you could easily make the CSS markup for each event and state, and duplicate what the previous website did with just CSS.

Here is an example. Right click and ’save as’ to save the source code.