mike
mike

Reputation: 749

how to write basic jquery if statement based on url

I don't know why this doesnt work. Although im sure its something to do with the way im handling the url in the if statement. My Jquery / javascript knowledge if basic.

var url = $(location).attr('href');

if (url == 'http://www.website.com/test/index.html')
{
  $('#HomeButton').bind('click', HomeButton);
} 

function HomeButton(e) {
e.preventDefault();

doSomething....

};

Upvotes: 3

Views: 6450

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382150

Don't use jquery to access standard object properties.

You can do

if (document.location.href == 'http://www.website.com/test/index.html')

but you should never compare to the whole URL : you'd have wrong result if you change your domain, test elsewhere, use https, add a parameter, etc. You should use the intended property of location, that is pathname :

if (document.location.pathname == '/test/index.html')

In case of doubt, if you want to be sure of your pathname, simply open Chrome's developer tools (by typing F12) and type this on the console : document.location.pathname.

Upvotes: 4

Alnitak
Alnitak

Reputation: 339816

window.location isn't a a DOM element so you can't use jQuery methods on it.

The .href is actually a property of a Location object.

Just use it direct - if (window.location.href === ...)

Upvotes: 1

Related Questions