-3

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')
    }
  • The question title does not have any relation with whatever you are asking. – ianaya89 Jan 21 '15 at 02:58
  • Which problem do you have? You don't know how to get the url of the page? You don't know how to add classes? You don't know how to add one class or another depending on the url once you got it? – Oriol Jan 21 '15 at 03:09
  • I don't know how to add one class or another depending on the url once I have it. – Garrett Sanderson Jan 21 '15 at 03:21
  • First off because you are checking if it equals. It should be == instead of just =. When you say just = it is an assignment operator whereas == is a comparison operator. – SharpCode Jan 21 '15 at 03:23
  • Thanks, missed that! It's working just how I want now. – Garrett Sanderson Jan 21 '15 at 03:24

1 Answers1

1
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.

SharpCode
  • 1,385
  • 3
  • 12
  • 29
  • Lol downvote for trying to help without an IDE... sweet *thumbs up* – SharpCode Jan 21 '15 at 03:00
  • Or window.location See: http://stackoverflow.com/questions/2430936/whats-the-difference-between-window-location-and-document-location-in-javascrip – Zze Jan 21 '15 at 03:00
  • Both work. Also @ianaya it is capital if you check the documentation. – SharpCode Jan 21 '15 at 03:03
  • 1
    The advantage of `location` is that you can access the different parts: `location.pathname`, `location.host`, `location.href`, ... – Oriol Jan 21 '15 at 03:06
  • There you go, might be better to use .location which can also be used via the document object or windows. But before you decide which object to use here is an interesting and helpful read http://eligeske.com/jquery/what-is-the-difference-between-document-and-window-objects-2/ – SharpCode Jan 21 '15 at 03:10