Why won't my jquery button disable

49 Views Asked by At

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';
    };
});

2

There are 2 best solutions below

6
Death-is-the-real-truth On BEST ANSWER

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

indexOf() functionality

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

1
Faraz Babakhel On

Verify that what is the value of window.location.href like

$("#homepage").on("click", function(event) {
alert( window.location.href);
});

than put this value in if condition like:

if (window.location.href === 'dummyrul/index.html') {
                $(this).attr('disabled', "disabled");
                $(this).attr('disabled', true);
                event.preventDefault();
            }