1

I'm trying to add a class to the body tag just on the homepage and that it. However, it's not working. What am I doing wring?

<script type="text/javascript">
    $(document).ready(function() {
          if(window.location.href===window.location.hostname) {
               $("body").addClass("home");
           }
    });
</script>
Xarcell
  • 2,011
  • 6
  • 33
  • 65

5 Answers5

3

window.location.href will never be the same as window.location.hostname since the former will contain protocol part (e.g.: http://) where as the latter doesn't.

Griffith
  • 3,229
  • 1
  • 17
  • 30
2

I don't think

if(window.location.href===window.location.hostname) {
}

will ever be true. hostname will host be something like stackoverflow.com where href will include protocol, ports and other things that may be apart of full url. You want to check if

if(window.location.href.indexOf("home.html") != -1) {
}

Or something of that nature. But as pointed out in comment this seems much simpler to just add to that html file or do it on the server if you generate the HTML.

AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43
2

window.location.href contains protocol information and will never equal window.location.hostname

As per W3

  • window.location.href returns the href (URL) of the current page
  • window.location.hostname returns the domain name of the web host
  • window.location.pathname returns the path and filename of the current page

You should rather check the pathname for home page location:

var path = window.location.pathname;
if (path == '/' || path == '/home.html') {
  $("body").addClass("home");
}
MaxZoom
  • 7,619
  • 5
  • 28
  • 44
0

It is possible without jquery very easy.

window.addEventListener("load", MyFunction);
function MyFunction(){
  if(window.location.origin == window.location.href) {
    var body = document.getElementsByTagName('body');
    body[0].className = "myclass";
  }
}

or

window.addEventListener("load", MyFunction);
function MyFunction(){
  if(window.location.origin == window.location.href) {
    document.getElementsByTagName('body')[0].className = "myclass";
  }
}

body[0] because document.getElementsByTagName return value is an array.

mstruebing
  • 1,674
  • 1
  • 16
  • 29
0

With the comments being made, it got me thinking. I tried this and it worked.

<script type="text/javascript">
    $(document).ready(function() {
        switch (window.location.pathname) {
          case '':
          case '/index.php':
              $('body').addClass('home')
        }
    });
</script>

I forgot to mention in the question that it is on a PHP powered website. I answered my own question to help others who one day might have the exact same question.

Xarcell
  • 2,011
  • 6
  • 33
  • 65