Liz
Liz

Reputation: 1048

How to add body class to front page & an internal page using jQuery?

The jQuery function below works properly, and adds a full class to the <body> HTML element on the /signin/ page based on the URL.

// add full class to sign in page body based on url

$(function() {
    var loc = window.location.href; // returns the full URL
    if(/signin/.test(loc)) {
    $('body').addClass('full');
  }
});

I want to accomplish the exact same thing on the front/home page, or / URL within this same function. How do I do this?

Upvotes: 0

Views: 230

Answers (2)

Dmitry Orlov
Dmitry Orlov

Reputation: 473

Regexes are slow. A faster way:

function() {
    var loc = window.location.pathname; // returns the pathname
    if(loc == '' || loc == '/') {
        $('body').addClass('full');
    }
});

Upvotes: 1

Vasif
Vasif

Reputation: 1413

Using an appropriate regex. /^\/$/in your case.

/^\/$/.test('/') // true
/^\/$/.test('/asdf')  //false

Further adding to it in your case. I would, use window.location.pathname

$(function() {
    var loc = window.location.pathname; // returns the pathname
    if(/^\/$/.test(loc)) {
        $('body').addClass('full');
    }
});

Upvotes: 0

Related Questions