jqueryhighlightcurrent-page

Highlighting current page item in the nav menu with jQuery


I've read all about this online but everything else was just overly complicated and I just want to implement a simple code that I can read without going into substrings and all that stuff, so i thought this might be a good challenge for as a noob in jquery. I've come up with this code but without success.

HTML

<ul id="nav">
    <li><a href="/" id="home" class="lettering">HOME</a></li>
    <li><a href="/about" id="about" class="lettering">ABOUT</a></li>
    <li><a href="/works" id="works" class="lettering">WORKS</a></li>
    <li><a href="/contact" id="contact" class="lettering">CONTACT</a></li>
</ul>

jQuery

$(document).ready ( function(){
    var path = window.location.pathname;
    $('#nav li a').each(function() {
        if( path = ("/"+this.id+"/") ){
            this.addClass('active');
        } else {
            ('#home').addClass('active');
        }
    })
})

I hope you guys don't flame me, my intentions are purely academic rather than getting results. What is the problem here? I'm not getting any error logs or anything btw.

edit: removed the trailing slashes(thanks Justin), also tried what Phrogz suggested but no luck. If anyone feels up to the challenge, the site is located @ egegorgulu.com


Solution

  • If anybody is wandering, I came up with the following function for this. Many thanks to GregL for his pointers, it helped me a lot.

    jQuery.noConflict()( function(){
        var $ = jQuery;
        var path = window.location.pathname;
        $('#nav li a').each(function() {
            if( path === "/" + this.id + "/" ){ 
                $(this).addClass('active'); 
            } else if( path === "/" ) {
                $('#home').addClass('active'); 
            }
        }); 
    });
    

    The reason for the noConflict is because I'm using an embedded contact form on my contact page. And I'm pretty sure that the second if is unnecessary but didn't want to remove it once I got it working properly.