Garrett Sanderson Garrett Sanderson - 6 months ago 10
HTML Question

Is there a JavaScript method that will allow me to give the body a certain css class depending on which html page the user is on?

I am trying to track what the URL the user is on and add a remove a class based on that URL. Can someone help me out?

Edit*

This is what I have right now and my page is just reloading

var $webPage = "http://localhost/collin-sanderson/";

if (location.href = $webPage) {
$('body').addClass('home')
}
else {
$('body').removeClass('home')
}

Answer
var $webPage = "http://localhost/collin-sanderson/";

    if (location.href == $webPage) {
        $('body').addClass('home')
    }
    else {
        $('body').removeClass('home')
    }

I have altered the code so it uses a comparison operator instead of an assignment operator. Assignment operators are used to write a value to a variable, on the other hand a comparison operator compares two variables like you require. See JavaScript Operators

Also here is a helpful/interesting read on the difference between document and window objects. Difference between document and window objects.

Comments