Home arrow JavaScript arrow Page 4 - Building a Dynamic Menu with CSS and Javascript, concluded
JAVASCRIPT

Building a Dynamic Menu with CSS and Javascript, concluded


Dynamic menus that highlight the link where a website visitor is located can make site navigation a much more pleasant experience. In this article, the second and final part of the series, we learn more about dynamic menus in JavaScript and then check out the menu class.

Author Info:
By: Alejandro Gervasio
Rating: 4 stars4 stars4 stars4 stars4 stars / 31
June 29, 2005
TABLE OF CONTENTS:
  1. · Building a Dynamic Menu with CSS and Javascript, concluded
  2. · Adventures with the Menu Class and Button Class
  3. · The Style Object
  4. · Another Class on the Road: Using the Menu Class

print this article
SEARCH DEVARTICLES

Building a Dynamic Menu with CSS and Javascript, concluded - Another Class on the Road: Using the Menu Class
(Page 4 of 4 )

As its name implies, the "Menu" class will take care of building the dynamic menu, invoking (as many times as we need) the constructor for the "Button" class. This will generate the complete menu structure progressively. Since the buttons are charged with the hard work, this class is pretty simple. Letís have a look at it:

function Menu(x,y){
     if(parseInt(x)!=x||parseInt(y)!=y){return;}
     // create menu <div>
     var menudiv=document.createElement('div');
     // create menu buttons
     var btna=new Button(x,y,80,15,'About us','about.htm');
     var btns=new Button(x+81,y,80,15,'Services','services.htm');
     var btnp=new Button(x+162,y,80,15,'Products','products.htm');
     var btnl=new Button(x+243,y,80,15,'Links','links.htm');
     var btnc=new Button(x+324,y,80,15,'Contact us','contact.htm');
     // insert menu buttons into menu container
     menudiv.appendChild(btna);
     menudiv.appendChild(btns);
     menudiv.appendChild(btnp);
     menudiv.appendChild(btnl);
     menudiv.appendChild(btnc);
     return menudiv;
}

As you can see, the class accepts only two parameters: the left and top coordinates to position the menu in the web page. Then, it creates a <div> element that will behave as the general menu container. With this object generated, all the class needs to do is create the button elements. This is easily achieved by instantiating as many new button objects, as we need for the project. In the above example class, Iíve created five buttons, assigning the proper left and top coordinates, specifying a width of 80px and a height value of 15px. Finally, Iíve assigned the texts and links for each of them.

Once the buttons have been generated, the job to be done is really a breeze. I just need to append them as child nodes to the menu containing <div>, and return the whole menu as an object. The only thing to do is instantiate a new "Menu" object, when the page is loaded and Voila! Iíve got a true dynamic menu, generated with only two simple JavaScript classes. The code might be something like this:

window.onload=function(){
     var menu=new Menu(10,10);
     if(document.body.firstChild){
          document.body.insertBefore(menu,document.body.firstChild);
     }
}

In this case, Iíve decided to position the menu at the left-top coordinates of 10px and 10px respectively, and insert it as the first element in the document structure. Obviously, itís highly recommendable putting the source code as a separated (.js) file, and then include it in all of the pages that reference it. As usual, the full code including the two classes is listed below:

function Button(x,y,w,h,text,url){
     if(arguments.length!=6){return;}
     // create button <div>
     var button=document.createElement('div');
     // create link
     var lnk=document.createElement('a');
     // get current location
     var loc=location.href;
     // style button <div>
     button.style.position='absolute';
     button.style.left=x+'px';
     button.style.top=y+'px';
     button.style.width=w+'px';
     button.style.height=h+'px';
     button.style.padding='3px 0px 3px 0px';
     button.style.textAlign='center';
     button.style.borderColor='#000';
     button.style.borderStyle='solid';
     button.style.borderWidth='1px';
     // resolve active page and display button differently
     loc.indexOf(url)!=-1?button.style.backgroundColor=
       '#fc0':button.style.backgroundColor='#9cf';
     // style link
     lnk.style.display='block';
     lnk.style.color='#000';
     lnk.style.fontFamily='Verdana';
     lnk.style.fontSize='11px';
     lnk.style.textDecoration='none';
     // assign attributes to link
     lnk.href=url;
     lnk.title=text;
     // change link color on mouseover
     lnk.onmouseover=function(){
                this.style.color='#fff';
     }
     // reset link color on mouseout
     lnk.onmouseout=function(){
                this.style.color='#000';
     }
     // insert text link
     lnk.appendChild(document.createTextNode(text));
     // insert link into button <div>
     button.appendChild(lnk);
     return button;
}
function Menu(x,y){
     if(parseInt(x)!=x||parseInt(y)!=y){return;}
     // create menu <div>
     var menudiv=document.createElement('div');
     // create menu buttons
     var btna=new Button(x,y,80,15,'About us','about.htm');
     var btns=new Button(x+81,y,80,15,'Services','services.htm');
     var btnp=new Button(x+162,y,80,15,'Products','products.htm');
     var btnl=new Button(x+243,y,80,15,'Links','links.htm');
     var btnc=new Button(x+324,y,80,15,'Contact us','contact.htm');
     // insert menu buttons into menu container
     menudiv.appendChild(btna);
     menudiv.appendChild(btns);
     menudiv.appendChild(btnp);
     menudiv.appendChild(btnl);
     menudiv.appendChild(btnc);
     return menudiv;
}
window.onload=function(){
     var menu=new Menu(10,10);
     if(document.body.firstChild){
          document.body.insertBefore(menu,document.body.firstChild);
     }
}

Donít you feel happy? The menu is really dynamic in a strict sense, because itís not only capable of indicating the active link, but itís been generated on the fly, using the native object-oriented capabilities of JavaScript. Just take a deep breath, relax, and enjoy the rest of the article.

Wrapping up

Over this two-part series, we have progressively created a dynamic menu that detects the active page and displays the corresponding link differently, visually indicating to the user what page is being visited. This real-world application is truly very handy to introduce us into the exciting arena of user-defined objects in JavaScript. Hopefully, this will be an open door to encourage web developers to take advantage of these powerful capabilities, often hidden from other common language features. Harnessing the power of object oriented JavaScript is something to be considered in any web projects where code reusability is a big time saver.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials