Getting URL breaks across chrome and firefox

I am trying to apply a background image to the body element by checking which page I am on, then adding a class (with a background-image property) based on the page that I am on i.e. index.php, book.php, library.php etc.

Currently, I am using the document.location object (i.e. document.location.href) and I have also tried the window.location object to no avail.

My problem is that Firefox returns the URL without a trailing hash (#) or question mark (?), whereas Chrome returns the url with these trailing characters whether or not there is any additional url following said characters.

Here is my code:

 switch(currentFileName()) {
case "index.php": bodyBackGroundFadeIn('home');
  break;
case "library.php": bodyBackGroundFadeIn('library');
  break;
case "store_library.php": 
bodyBackGroundFadeIn('store_library');
  break;
case "book.php": bodyBackGroundFadeIn('book');
  break;
case "store_book.php": bodyBackGroundFadeIn('store_book');
  break;
  }

function currentFileName(){
var href = document.location.href;
return href.substr(href.lastIndexOf("/") + 1);
}


function bodyBackGroundFadeIn(class_name){

 $(document.body).addClass(class_name);
 $(document.body).animate({opacity: 1.0},'600');

}

Is there a better way to achieve this effect? I have considered using a regex to search for a '?' or a '#' but I don't want to mess with this if it isn't cross-browser.

I have also tried using bitwise operators to invert an empty hash value to make this work across Firefox and Chrome but that didn't work either.

Here is the output from Firefox:

>> document.location.href.substr(href.lastIndexOf("/") + 1);
"index.php" 

Here is the output from Chrome:

>> document.location.href.substr(href.lastIndexOf("/") + 1);
"index.php?"

There is also this thread which offers a number of ways to concatenate and deduce strings, however no method to deal with this specific issue.

Answers:

Answer

You should just be using pathname

window.location.pathname.split("/").pop()

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.