views:

161

answers:

1

I'm looking for something similar to this: http://stackoverflow.com/questions/302955/active-navigation-with-jquery-cant-apply-a-default-class-to-anchor

But I'm using images inside a unordered list and I want to detect the current URL and append the img src with _over.jpg to show it being the current page. (no lectures on using BG position please - the client likes this.)

I'm also using this easy hover (jQuery mouseover), which I bet will need to be adjusted...

$(document).ready(function(){

    $(".navbar li").each(function(){
        var link = $(this).children("a");
        var image = $(link).children("img");
        var imgsrc = $(image).attr("src");

        // add mouseover
        $(link).mouseover(function(){
            var on = imgsrc.replace(/.jpg$/gi,"_over.jpg");
            $(image).attr("src",on);
        });

        // add mouse out
        $(link).mouseout(function(){
            $(image).attr("src",imgsrc);
        });
    });

});
+1  A: 

The magic is in document.location.pathname :P

$(document).ready(function(){
    $(".navbar li").each(function(){
        var link = $(this).children("a");
        var image = $(link).children("img");
        var imgsrc = image.attr("src"); //no need to rewrap in $

        var on = imgsrc.replace(/.jpg$/gi,"_over.jpg");
            if (link.attr("href") == document.location.pathname || link.attr("href") == document.location.href)
            $(image).attr("src",on);
            else
                // add mouseover
                $(link).hover(function(){
                    $(image).attr("src",on);
                }, function(){
                    $(image).attr("src",imgsrc);
                });
    });
});

Why two conditions ORed in the if? Internet Explorer will return hostname (document.location.href) and Firefox/WebKit will return exactly what’s written on your link. But I would test for cross-browser issues if I was you.

matdumsa
That rocks and works too! Big Thanks.Not too sure what you mean by "two conditions ORed in the if??"Now, I'm wondering if we have variables behind a URL, like from a CMS pulling in article names, will the jquery still write _over.jpg to the nav img src?
Lorenzo816