Dhananjay
Dhananjay

Reputation: 211

change class on the basis of URL using jquery

I am working in wordpress, I am using jquery to add remove class in body tag.

I want to apply class "home" to homepage and for other pages I want to apply "innerpage" class to body tag.

following is my code.

$(document).ready(function(){
var loc = window.location.href; // returns the full URL
//alert(loc);   
if (loc == "http://n.net/") 
    {
        $('body').removeClass('innerpage').addClass('home');
        $('.widget-area').removeAttr('style');

    }else {
        $('body').removeClass('home').addClass('innerpage');
        }


});

but it is not working if the url comes like: http://n.net/?=s

Upvotes: 0

Views: 319

Answers (3)

Manu M
Manu M

Reputation: 1064

Try this,

$(document).ready(function(){
var loc = window.location.href; // returns the full URL
//alert(loc);   
if (loc.split('.net')[1] == '/' || loc.split('.net')[1] == '') 
{
    $('body').removeClass('innerpage').addClass('home');
    $('.widget-area').removeAttr('style');

}else {
    $('body').removeClass('home').addClass('innerpage');
    }


});

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78525

If you only want to match the path, use pathname instead:

var path = window.location.pathname;
if(path === "/") {
  // Homepage
  $('body').removeClass('innerpage').addClass('home');
  $('.widget-area').removeAttr('style');
}
else {
  // Other pages
  $('body').removeClass('home').addClass('innerpage');
}

This will match for:

http://n.net/

http://n.net

http://n.net/?a=1

http://n.net/?a=1#hash

Have a look at all the properties of the location object, it contains a lot more than just href

Upvotes: 2

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

If you just want the URL, without the querystring, use this...

window.location.href.split("?")[0];

Upvotes: 0

Related Questions