Javascript menu demo

Various ways of doing a menu where mouse over highlights an option.

View Source to see full CSS and JS.





CSS change element background-color

CSS code like the following can change an element background-color on hover. No JS needed:

button.menubutton:hover 
{
	background-color: lightyellow;
}





JS change img src

The onmouseover event can call JS, which can then carry out arbitrarily-complex calculations and changes.
The following uses pre-prepared images. The JS switches img src to a different image on hover.
Images made at ButtonGenerator.com.


<a onmouseover="document.getElementById('menu1').src='menu.1.on.png';" 
    onmouseout="document.getElementById('menu1').src='menu.1.off.png';"
 href="file.html"><img src="menu.1.off.png" id="menu1"></a>






JS change img src (cleaner)

Here is a version of the above with the JS better separated from the HTML.
We define elements in the HTML first, with no JS.
Then the JS finds elements and applies event handlers to them.
View Source.


function setHover ( id, onimg, offimg )		// set hover on and off images for this element ID 
{
    document.getElementById(id).onmouseover = function() { this.src = onimg;  };
    document.getElementById(id).onmouseout  = function() { this.src = offimg; };
}

This is called Unobtrusive JavaScript






CSS change img src (works on Chrome)

As CSS has evolved, it has taken over some of the things you once might have needed JS for. In fact, CSS can now change the img src itself. No JS needed:

#css1:hover 
{
 content:url("menu.1.on.png");
}





CSS is a simpler solution than JS

As a rule of thumb, doing something in CSS (not programming) is generally simpler and easier to maintain than doing it in JS (programming), if possible.
  


JS needed in menu for what?

Can you think of a menu effect we need JS for, that cannot be done in CSS?