Main Points

Unobtrusive Javascript Example 6

OK, the code for this page is identical to the last page. Example 5 didn't make any use of the menu divs, but they were there already. So there was no need to modify any of the underlying XHTML of the page. Here's one of the golden reasons to use unobtrusive Javascript. I only had to adjust the Javascript in the .js file to get new behavior. There is one piece of information about this code you need to know. Every button has an id, Button 1 has the id button01, Button 2 has the id button02...

<div class="navbutton" id="button01">
Button 1
</div>

And the menu attached to each button as a corresponding id. So the button with id button01 triggers the menu with id menu01, and the button with id button03 triggers the menu with id menu03.

Now what we want to happen is that when someone mouses over the button, its menu should appear, ie the menu's display should change from none to block. If you then mouse over the menu, it should remain display block. But if you leave EITHER then the menu should disappear, ie the display should change back to none.

What I've done is the same as the last example. I detect the ID of the object that triggered event. What I changed was that I no longer get the element with the id. I use a substring method to return the last two digits of the element.

var itemSuffix = item.substring(item.length-2,item.length);

I then get the element which has the id menu + those final two digits. This has the result that whether it's button01 or menu01 that is moused over, menu01 is the element retrieved. This block of code which returns the menu with the proper id is the core of the revised ButtonOff function...

// Grab the Div
myMenu = document.getElementById("menu" + itemSuffix);
myMenu.style.display="block";

Then all I had to do was copy the subroutine and modify it to turn the menus on, ButtonOn. I set the display from none to block and I call ButtonOn whenever there is a onmouseover event. This completes my navbar development, at least for the moment.

Skip to Main Points
Continue to 7. Oops! Adding Links-->