I wanted to make a dynamic navigation bar that could identify the current page by highlighting the image buttons border that is related to the page it is on. For example, on the index.html the homeButton.jpg is highlighted. I would like this to be dynamic and not statically coded. I am using templates I would like the main content to be the only thing editable.
This is my HTML code for the navigation bar:
<ul id="navbar">
<li><a href="../index.html" ><img id="theImg" src="../images/Buttons/homeBtn.jpg" name="homebtn" alt="Home" border="0" /></a></li>
<li><a href="../pages/about.html"><img src="../images/Buttons/aboutBtn.jpg" alt="About" border="0" /></a></li>
<li><a href="../pages/mediapages/media.html"><img src="../images/Buttons/mediaBtn.jpg" alt="Media" border="0" /></a></li>
<li><a href="../pages/downloads.html"><img src="../images/Buttons/downloadBtn.jpg" alt="Download" border="0" /></a></li>
<li><a href="../pages/contactpages/contacts.html"><img src="../images/Buttons/contactBtn.jpg" alt="contact" border="0" /></a></li>
<li><a href="../pages/blog.html" target="_blank"><img src="../images/Buttons/blogBtn.jpg" alt="blog" border="0" /></a></li>
</ul>
and the JavaScript code:
var examplehtml = [['http://example.com/'],['http://www.example.com/']];
var navRoot = document.getElementById("navbar").getElementsByTagName("img");
var currentpage = document.location.href;
if(currentpage == examplehtml [0] || currentpage == examplehtml [1] ){
navRoot[0].src = "../images/Buttons/homeBtn2.jpg";
return;
}
var indexpage = currentpage.search(/index.html/);
var aboutpage = currentpage.search(/about.html/)
var mediapage = currentpage.search(/mediapages/);
var downloadpage = currentpage.search(/downloads.html/);
var contactpage = currentpage.search(/contacts.html/);
var commentsentpage = currentpage.search(/comment_sent.html/);
if(indexpage>-1){navRoot[0].src = "../images/Buttons/homeBtn2.jpg";return;}
if(aboutpage>-1){navRoot[1].style.border='1px solid #fff';return;}
else if(mediapage>-1){navRoot[2].style.border='1px solid #fff';return;}
else if(downloadpage>-1){navRoot[3].style.border = '1px solid #fff';return;}
else if(contactpage>-1){navRoot[4].style.border='1px solid #fff';return;}
else if(commentsentpage>-1){navRoot[4].style.border = '1px solid #fff';return;}
}
window.onload = Getcurrentpage;
I was wondering is there a better way of doing this or anything I can do to improve performance?
Keep your JS and CSS separate; first off put that styling in the CSS:
CSS:
HTML:
JS:
Here’s a live example.