JavaScript / jQuery Page Identifier Tutorial

This is the first of hopefully many Web technology related blog posts I'll be writing. More specifically these articles will be involving JavaScript / jQuery and Cascading Style Sheets (CSS).

In this tutorial I will be using JavaScript to analyze which Web page a user is viewing and then apply a CSS style to the relevant menu element to provide the audience some visual feedback. Please download jQuery as it is requited for this example. I often use the library to simplify parts of my code and to gain some benefits like not having to worry as much about coding cross browser compatibility.

First off, let's take a look at exactly what we're trying to do (click the pic for a larger size).


Take a look at the URL bar. You'll see that it contains the text, "www.imrezbalint.com/videos.php". Now look at the navigation bar of my site. See how the VIDEOS link is highlighted? Well that's the work of the script we're about run through.

Now you're probably thinking, I could just as easily do this using CSS by placing an inline style on that link (or a class) on each page that needs it. True, manually you could. But you'd have to remember to do this on every new page you might at one time want to add to your site. Did I mention you have to do this manually? Yuck!

With JavaScript there's a cooler and better way (well I think it's better).

But before hitting the code, let's examine the markup first as this helps us understand what we'll be doing. The pertinent piece is really just the menu.

<nav>
    <a href="index.php" id="index">HOME</a>
    <a href="about.php" id="about">ABOUT</a>
    <a href="resume.php" id="resume">RESUME / C.V.</a>
    <a href="videos.php" id="videos">VIDEOS</a>
    <a href="music.php" id="music">MUSIC</a>
    <a href="resources.php" id="resources">RESOURCES</a>
    <a href="contact.php" id="contact">CONTACT</a>
</nav>

Nothing all that spectacular. Just a nav element and within it nested are a bunch of anchors. I have them styled as blocks to get the look I want for my navigation bar; that's why you see all those ids (I had to mess with the widths of a few of the menu items to get them to look just the way I wanted them).

Now let's take a peek at the script:

$(document).ready(function() {
    var docLoc   = document.location.toString();
    var index    = docLoc.lastIndexOf("/");
    var strPage  = docLoc.substring(index+1);
   
    if (docLoc.length < 28) {
        strPage  = "index.php";
    }
   
    $("nav a").each(function() {
        if ($(this).attr("href") == strPage) {
            $(this).css({"background-color": "#777"});
            return false;
        }
    });
});


Considering what is being accomplished, this is not a lot of code. First off we have:

$(document).ready(function() {

This is a fairly common method to start off a jQuery script to initialize things when the document object model is ready to be manipulated. In more plain English, we're saying that when the page is ready to be worked on, execute the following code in the anonymous function.

Next we have three variables to store some information we need. docLoc contains a string of the URL. We cannot just use "document.location", as this will only return the location object with other functionality we are not interested in for this purpose.

The next two variables are index and strPage. The variable index is used to get the position of the last forward slash in the URL, and strPage basically stores the file name we need by using the substring function. When passing one argument to the function, in this case a value of index+1, a new string is created starting from that position in the string and up to the end. Why the plus one? Because I don't want to include the slash. Take a look back above at the navigation HTML. The hrefs point to a file name like, "index.php". Anyway, when all is said an done, the strPage variable holds the file name to a page on my website.

if (docLoc.length < 28) {
    strPage  = "index.php";

}

This quick conditional statement performs a check to see if there's no file name in the URL. For example, someone might enter my website via, http://www.imrezbalint.com/. Notice how there is no file name at the end (no index.php). In such situations I'd still like to ensure that the HOME link on my website is highlighted. It just so happens that the URL as you just saw written is 27 characters, hence why I'm checking to see that if the length of the document location (stored in the variable docLoc) is less than 28 characters, then I set the strPage variable to the home page, index.php. We'll need this for the next section.

Here's where the fun and automation really kicks in. One the things I really like about jQuery is the CSS-like method of selecting elements on a page. Since I'm only interested in the links nested in the nav section of my pages, I use the $("nav a") selector.

The each function then allows me to loop through, you guessed it, each of the links in that nav section.

if ($(this).attr("href") == strPage)

With the if statement above I can then check the link's hyperlink reference to see if it equals whatever is in the strPage variable. If that condition is true:

 $(this).css({"background-color": "#777"});
return false;

These two lines finish the rest of the script off. The $(this) part of the code refers to the current link (in the nav section) that the each loop is working on. The css function then adds the highlight as a background colour to that link. The return; statement ends the each function from executing any further as it would be waste of processor time; the logic is that there is only one menu item that should match, so once it's found, stop the loop from continuing.

And there you have it. If you have a website developed in a similar fashion then this script might be helpful to you either almost as is or with a little modification if necessary.

I have several more of these tutorials lined up and I'm hoping to keep up a pace of one a week. We'll see how that goes. If you have any suggestions for future tutorials, I'm willing to listen so just leave a comment. L8r!

Comments

Popular posts from this blog

Protostar: Error in Transmission - New Web Novel Published!

Part 2: Time-lapse Photography - Photography with Imre - Episode 36

Circulum - My Science Fiction Novel - Ready to Enjoy!