Change Link Color Via Javascript
Im playing around with a pure HTML site recently (no server side tech at all) and OMG how akward is the simple stuff. To make my life a little more easier I have been using Dreamweaver's templates which make managing layouts easier especially when you have forgotten a navigation link.
One thing I have been trying to do is change the colour of a selected navigation link. i.e. The navigation links are all blue except for the link to the section you are currently in which is white. I was about to do this with DWMX templates conditional statements, which can get a little messy, and awkard when putting them inline to change the href class atrribute. Doing this with CFMX or PHP is simple and thats what I wanted.
So I took a dynamic(ish) approach to the problem and decided to use Js. Reading in the page name from the window.location.pathname string I change the colour of the text. Incase anyone is interested below is the code I used, you'll note that to do this without a switch or if statement I have used the ID attribute, and made it the same as the html page.
2<head>
3<InvalidTag>
4function linkHighlight(){
5 var urlPath = window.location.pathname;
6 var thisPage = urlPath.substring(urlPath.lastIndexOf('/') + 1);
7 var pageName = thisPage.split('.');
8
9 document.getElementById(pageName[0]).style.color = '#FFFFFF';
10}
11</script>
12</head>
13<body>
14<a href="index.htm" id="index">Home</a>
15<a href="products.htm" id="products">Products</a>
16<a href="projects.htm" id="projects">Projects</a>
17<a href="about_us" id="about_us">About Us</a>
18<a href="contact_us.htm" id="contact_us">Contact Us</a>
19</body>
20</html>
| Tweet |
| If you like what you see on the website and/or this post has helped you out in some way please consider donating to help keep me in beer vodka. The donations are made through Paypal, which accepts almost any credit card or eCheck. |
This is very close to something I've been trying to execute on my search engine. I want all links that contain "AS BID" in the URL to be green, and links containing "AS BUILT" in the URL to be blue. Is it possible with a tweak of your code? It seems so close.
Thanks,
Zadok
for (,) for it to show up as foo.asp and not foo,asp. Anyhow,
Used this to write header include file with a css menu. This reads the name of the page, sees which of the <li> item links it matches
and then changes the background colour using the corresponding id to make sure the current option worked even though the whole
thing is an include.
Cheers again... I credited you in my script comment