Monday, March 7, 2016

Highlight the active link on a single HTML page using jQuery and Bootstrap

In a web page, it is useful to indicate the active page (or photo or whatever) in the navigation links by changing some style to differentiate it from the other links. An example is the Photo 4 link in the screenshot below.
When the user clicks on another item, the other link e.g. Photo 5 is highlighted and the previously active link becomes a normal link again, as shown below.
I wanted to do the same but on a single page without resorting to server side programming. This can be done with some help using jQuery, Bootstrap, HTML and some custom CSS styles. Bootstrap can be downloaded from http://getbootstrap.com/. jQuery can be downloaded from https://jquery.com/

1. In the HTML page, set up the links with the nav semantic tag with the Bootstrap classes navbar, navbar-nav as shown below. A unique id e.g. main-nav should be assigned also.

3. To tie the HTML and the styles, create a Javascript function as shown in the code snippet below with jQuery to search for the navigation link elements with the id (main-nav) assigned previously and add a click event handler to each link. When the user clicks on a link, the function will get the active link element and remove the active class style from it. Then add the active class style to the clicked link.