AndyJarrett Code. Develop. Manage.

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.

function linkHighlight(){ var urlPath = window.location.pathname; var thisPage = urlPath.substring(urlPath.lastIndexOf('/') + 1); var pageName = thisPage.split('.'); document.getElementById(pageName[0]).style.color = '#FFFFFF';}HomeProductsProjectsAbout UsContact Us
I’m here, learning and working away. If you liked this content and want to keep me going, consider buying me a coffee.
Your support keeps this site running and the coffee brewing! ☕️