3

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

};
0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

7 Comments

You can also just use the click() method instead of binding to a function... $('#HomeButton').click(function(){ //do stuff });
@Conner actually, canonical jQuery is now .on('click', ...)
Ok then .on('click', function(e) { //do stuff });
im actually having trouble with the if check... so this works: if (window.location.href === 'website.com/test/index.html') but only if someone navigates using no www in the address...If someone does, the function wont work. is there a way to say: if (window.location.href === 'website.com/test/index.html' and 'website.com/test/index.html') ????
for some reason in my example above the comment is only showing website.com/test when, on the last link shown, it should have a www infront of it. So basically i was asking if there was a way to account for both urls in the IF statement? Both URLS being website.com and website.com with a www infront of it
|
1

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 === ...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.