Current Page TutorialAlright I haven’t done a post in about ten days so I thought I would go through some of my quick code examples. This example uses JavaScript to get the current page and apply a style to the current in a simple navigation. I haven’t styled anything just gave the barebones to prove functionality.

This does not require much code at all really and as with any good JavaScript one doesn’t need to touch the markup at all. The HTML & CSS are self explanatory and basic so let’s take a look at the JavaScript. The first thing we need to do is get the current page’s URL. I just condensed this code into a function. It works where we are calling the function without a problem.

Alright now in this function we can get the location of the page. Wrapping it in jQuery tags allows me to use the jQuery method to get the href attribute.

var loc = $(location).attr('href');

This returns the whole url with the protocol (http://) and all.

What we are interested in is the page name just index.html or page.html for example. The first step in doing that is breaking up the url to get index.html (page.html, etc.) by itself. We can do this by splitting the whole location by the / character.

var splitUrl = loc.split("/");

This will store each segment in a single array. So being as our page name is at the end of the location string it will be the last item in our array containing everything after the last /. var page = splitUrl[splitUrl.length - 1];

Lastly there is a ternary operator (a shorthand if statement to determine if the last item is empty. If it is empty that means we are on our homepage (index.html) so that link should be active.

page = (page =='') ? 'index.html' : page;

You may see an example here.

All of the source code is below: