I'm designing a website and I would like to add a certain class to a navigation element based on the document title. I currently have the following javascript. The nav elements have separate ids (the About Us nav element has the id="about" and so on)
<code>
window.onload=function(){
var docTitle = document.title;
var about = document.getElementById("about");
var advising = document.getElementById("advising")
if (docTitle = "About Us") {
about.setAttribute("class", "current");
about.setAttribute("className", "current"); // for IE which does not recognize "class"
return;
}
else {
about.setAttribute("class", "top_link");
about.setAttribute("className", "top_link"); // for IE which does not recognize "class"
}
if (docTitle = "Career Advising") {
advising.setAttribute("class", "current");
advising.setAttribute("className", "current"); // for IE which does not recognize "class"
return;
}
else {
advising.setAttribute("class", "top_link");
advising.setAttribute("className", "top_link"); // for IE which does not recognize "class"
}
}
</code>
The class change works
The problem seems to be that the if statement is true whether or not the document.title ="about" or anything else, (if I remove the return, both about us and advising elements have their class changed.
I might be the newest member at this moment.
So, -Greetings to every one!
I do JavaScript since the summer of 1996, and I think I've learned some good coding practices during these years, that I'd like to share.
To the topic:
-Assuming that, "About Us" is a different page from the "Advising..." one, and that your Top Links are using "top_link" class as default , -the only thing you need to do would be to accent the current link one leaving others undisturbed.
Also, (assuming that) your naming principle is as precise as seen here, I propose you try something like this (following script and approach).
Code:
window.onload=function(){
var docTitle = document.title.split(" ")[0];
var current = document.getElementById(docTitle);
current.className="current"
}
Bookmarks