[JavaScript+CSS+PHP] Changing style of actual menu link
I was looking for a way to change the style of the actual menu link (the last clicked link in the menu), so that the user could know what page he is seeing, or the last link he clicked. My first attempt was to use only CSS, but i didn’t find anything. Then i read somewhere that it was not able to what i wanted only with CSS, that i needed JavaScript to do it. Well, i’ve done it and here i’ll teach how to do it:
The first thing we have to do is to create the menu and it’s style:
Style:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #menu { border-top: 2px solid black; border-bottom: 2px solid black; padding: 10px; text-align: center; width: 300px; } #menu a { padding: 10px; text-decoration: none; margin: 0px 5px; color: black; background-color: "white"; } #menu a:hover { text-decoration: underline; } |
Note that i didn’t set the a:visited style.
Menu:
1 2 3 4 5 |
Now we have our menu, but it’s still not showing what is the actual menu link, so we will need a function that will change the style of the actual menu link:
Javascript Function:
1 2 3 4 5 | function setActualLink(item) { item.style.backgroundColor = "black"; item.style.color = "white"; } |
Now that we have the function it’s necessary to make it be executed after the menu is loaded, adding this line:
You could also create a class for the actual menu link and assign the class to the actual menu link, instead of setting the styles directly inside the javascript function, as shown below:
Actual Menu Link Class:
1 2 3 4 | #menu a.actualLink:visited { background-color: black; color: white; } |
And the javascript function would change to:
JavaScript Function:
1 2 3 4 | function setActualLink(item) { item.className = "actualLink"; } |
You can see the examples in the links below:
Using class
Not using class
The php codes are commented in the source.
Remeber that the pages must be .php .
:wq




