Sorry if this sounds like a really stupid question, but I need to make a link change color when you are on the page it links to.
For example, when you are on the "Questions" page of stackoverflow, the link at the top changes color. How do you do this?
If for some reason you don't want to handle this on the server-side, you can try this:
It really depends on how your page is constructed. Typically, I would do this using CSS, and assign give the link an id called "active"...
...and in the CSS...
Obviously this is a fairly simplistic example, but it illustrates the general idea.
Set a class on the body tag for each page (manually or server-side). Then in your CSS use that class to identify which page you're on and update the style on the item accordingly.
Here's a good longer explanation
Server side code is the easiest, by just setting a class on the link on the current page, but this is also possible on the client-side with JavaScript, setting a second class on all elements in a particular class which have an href which matches the current page.
You could use either document.getElementsByTagName() or document.links[] and look only for those in a class denoting your navigation links and then set a second class denoting current if it matches the current URL.
The URLs will be relative, while document.URL will not. But you can sometimes have this same problem with relative vs. absolute on the server-side if you are generating content from a table-driven design and the users can put either absolute or relative URLs anyway.
You need code on the server for this. A simplistic approach is to compare the URL of the current page to the URL in the link; however consider that there are many different URLs in stackoverflow which all result in the 'Questions' tab being highlighted.
A more sophisticated version can either put something in the session when you change pages (not too robust); store a list of pages/URL patterns which are relevant to each menu item; or within the code of the page itself, set a variable to determine which item to highlight.
Then, as John Millikin suggests, put a class on the link or on one of its parent elements such as "current-page" which will control the colour of it.
You can do this without having to actually modify the links themselves for each page.
In the Stack Overflow clone I'm building with Django, I'm doing this:
Then filling in the
bodyclass
like so in page templates:Then, with the following CSS, the appropriate link is highlighted for each page: