开发者

Detect if visitor is on index page with client side scripting

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 visito开发者_开发技巧r is on the home page or not.

Non-index page:

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

Index page:

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


An other solution , without Base URL.

if ( window.location.pathname === '/' ){
    //code for index page

}else{
    //other tasks    
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜