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 == '.html')
{
$('#HomeButton').bind('click', HomeButton);
}
function HomeButton(e) {
e.preventDefault();
doSomething....
};
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./test/index.html')
{
$('#HomeButton').bind('click', HomeButton);
}
function HomeButton(e) {
e.preventDefault();
doSomething....
};
Share
Improve this question
edited Jul 9, 2012 at 7:42
Denys Séguret
383k90 gold badges811 silver badges776 bronze badges
asked Jul 9, 2012 at 7:38
mikemike
7492 gold badges13 silver badges24 bronze badges
0
2 Answers
Reset to default 4Don't use jquery to access standard object properties.
You can do
if (document.location.href == 'http://www.website./test/index.html')
but you should never pare 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
.
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 === ...)