Menu

Highlight the Current Page with jQuery, CSS & PHP
📰

Highlight the Current Page with jQuery, CSS & PHP

DEV Community: css·Kevinleary.net·12 days ago
#ElSrtVjy
#devtocss#devto#dev#navigation#jquery
Reading 0:00
15s threshold

Here’s a common web development scenario: How do we highlight the current page in a navigation seamlessly and dynamically? The answer is jQuery.

See a Live Demo

My recipe for this common scenario involves a mixture of CSS and JavaScript with a dash of jQuery.

HTML

<ul id= "navigation" > <li><a href= "https://www.kevinleary.net/about/" > About </a></li> <li><a href= "https://www.kevinleary.net/services/" > Services </a></li> <li><a href= "https://www.kevinleary.net/blog/" > Blog </a></li> <li><a class= "active" href= "https://www.kevinleary.net/contact/" > contact </a></li> </ul>

Enter fullscreen mode

Exit fullscreen mode

JavaScript / jQuery

$ ( function (){ $page = jQuery . url . attr ( " file " ); if ( ! $page ) { $page = ' index.html ' ; } $ ( ' #navigation li a ' ). each ( function (){ var $href = $ ( this ). attr ( ' href ' ); if ( ( $href == $page ) || ( $href == '' ) ) { $ ( this ). addClass ( ' on ' ); } else { $ ( this ).…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.