Javascript: How to un-disable buttons when 'back' button is pressed

Viewed 472

I have buttons, that upon being clicked, will take the user to another page, and before doing so, will become disabled

$(this).prop('disabled',true);

When the user clicks on the 'back' button on some browsers (e.g. Firefox and iOS Safari), the button will still be disabled. I'd like the button to continue to be disabled upon click, but then to be NOT disabled if the user returns to the page (whether it's by the 'back' button or other means). How can I do this?

Thanks

2 Answers

Just enable buttons when document is ready:

$( document ).ready(function() {
    $( "button" ).prop( 'disabled', false );
});

adding window.addEventListener("beforeunload", function() {}); will force Firefox to behave like Chrome:

const appEl = document.body;
const buttonEl = document.createElement("button");
buttonEl.textContent = "button";
buttonEl.addEventListener("click", () => {
  const pEl = document.createElement("p");
  pEl.textContent = "changing page in 1 sec";
  appEl.append(pEl);
  setTimeout(() => (window.location = "//example.com"), 1000);
  buttonEl.disabled = true;
});
appEl.append(buttonEl);

window.addEventListener("beforeunload", function() {});

Related