Skip to content
Advertisement

Change which a-tag is highlighted depending on active page

So I have a menu with different items

JavaScript

The class="active" highlights the menu item, and I was wondering how I could make this class change depending on which page I was on. So if the user visited Archives, then that has class="active".

The class is just a simple color

JavaScript

items

All my html code is run inside php files.

UPDATE

Might have found something that works, using php, what do you guys think?

Made a php script which checks what page I’m on, and writes active or not in my a-tags.

JavaScript

Advertisement

Answer

Since I dont use the .php on my pages, I remove that part from the filename. Beside that I use the basename of PHP_SELF, to get the name of the current file. If that is equal to the name in the menu function, then write active. Only problem here would be if I had two files with same name in different directories, and added them to the menu. Because then both would be highlighted, which is why I added basename(getcwd()), to get the parent directory, then also includes that the function should be called with it’s parent name like active('website/index')

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement