views:

54

answers:

1

Is it possible to detect if a visitor is on the index page or domain root with client side scripting?

I figure javascript would be the best method as I would like to append a value to an image file based on wether a visitor is on the home page or not.

Non-index page:

<img src="/img/logo.png" />

Index page:

<img src="/img/logo-home.png" />
+5  A: 
var homeUrl = 'http://www.example.com';
if ( document.URL == homeUrl ){
    // true
}else{
    // false    
}

Now put an id on your image tag in the HTML:

<img src="/img/logo-home.png" id="logotype" />

Now you can easily find the image tag with javascript and change the source of the image depending on where you are on the site.

$(document).ready(function(){

    var homeUrl = 'http://www.example.com';
    var logotypeHome = '/img/logo-home.png';
    var logotypeGeneral = '/img/logo-general.png';

    if ( document.URL == homeUrl ){
        $('#logotype').attr("src", logotypeHome);
    }else{
        $('#logotype').attr("src", logotypeGeneral);   
    }

});

I would still strongly recommend to go for a server-side solution for a thing like this. If the client doesn't have JavaScript enabled this will not work. Also there could be a flash on the image when the javascript changes the logo source.

Fred Bergman
`document.location.href` is what you're looking for.
Jacob Relkin
Brilliant. How would I go about setting a value and writing that to the document?
sterling
Don't forget the check the index file too if there is one ... http://www.example.com/index.php or http://www.example.com/home/ might be the homepage too.
ChrisR
@sterling - I could be wrong, but I'm guessing what you really need is a server-side scripting language. Using Javascript to tweak things like this on 99% of your pages doesn't seem like a great idea.
scunliffe
@scunliffe - I agree, there are many ways this could be accomplished server side, but in this specific scenario on a very small site, I am looking for a client side solution. Thank you for your input.
sterling
Come on, with 0% accept rate, I won't waste my time answering his question.
Helen Neely
How do I accept an answer?
sterling