I'm trying to disable a button if the user is currently on that page, I know there is more efficient ways but i am practicing my if, elses.
The problem is that I am still able to click the links and both will refresh the page if I click them and i'm on the same page. My code:
$("#homepage").on("click", function(event) {
if (window.location.href === 'index.html') {
$(this).attr('disabled', "disabled");
$(this).attr('disabled', true);
event.preventDefault();
}else {
window.location.href = 'index.html';
};
});
$("#aboutUs").on("click", function(event) {
if (window.location.href === 'aboutus.html') {
$(this).attr('disabled', "disabled");
$(this).attr('disabled', true);
event.preventDefault();
}else {
window.location.href = 'aboutus.html';
};
});
Actually window.location.href
will give you full-fledged URL like:-
https://www.example.com/index.html
http://www.example.com/index.html
etc.
That's why it seems that your if
condition never becomes true.
Use indexOf()
like below:-
$("#homepage").on("click", function(event) {
if (window.location.href.indexOf('index.html') >-1) {
$(this).prop('disabled', true); // recomended to use `prop`
event.preventDefault();
}
else {
window.location.href = 'index.html';
}
});
$("#aboutUs").on("click", function(event) {
if (window.location.href.indexOf('aboutus.html')>-1) {
$(this).prop('disabled', true);// recomended to use `prop`
event.preventDefault();
}
else {
window.location.href = 'aboutus.html';
}
});
Reference:-
If you want to disable buttons on only two specific URL'S then use full path in your if
condition provided by console.log(window.location.href);
.