-2

Why doesn't this work, I want it to show me "sure to proceed?" When I click the button to which the ".collect" class is attached.

const button = document.querySelector(".collect");
button.addEventListener("click", function() {
    alert("Sure to proceed?");
});
<button type="submit" class="collect">PROCESS</button>

Executing the JavaScript after the target element solves the problem, refer to the post anchored to @David 's comment. Thanks.

Mr Pain
  • 1
  • 4
  • 2
    There could be a number of reasons this isn't working. Can you please edit the question to include the relevant HTML – Rory McCrossan Oct 05 '22 at 12:30
  • Ok I'll do that – Mr Pain Oct 05 '22 at 12:32
  • [Works for me.](https://jsfiddle.net/2o7r3nv9/) Can you provide a [mcve] which demonstrates the problem? *As a guess*, perhaps this code is executing before the target element exists? Or perhaps there's more than one target element? – David Oct 05 '22 at 12:32
  • I have just one tag with the collect class, and just one button tag in the whole page – Mr Pain Oct 05 '22 at 12:35
  • @MrPain it seems you want a `confirm` box not an alert ? – ThS Oct 05 '22 at 12:35
  • I run the code on chrome and it doesn't work. – Mr Pain Oct 05 '22 at 12:36
  • @ths would confirm work in place of alert there? – Mr Pain Oct 05 '22 at 12:37
  • 1
    @MrPain: Your code demonstrably works here in the question. So far my best guess is that you're [executing the JavaScript before the target element exists](https://stackoverflow.com/q/14028959/328193). But that's only a guess, since the problem isn't observable here. – David Oct 05 '22 at 12:37
  • @MrPain that depends on your requirements. Do you want the user to confirm before moving away and cancel the action if the user cancels ? – ThS Oct 05 '22 at 12:38
  • @David you were right, I put the script after the target and it worked. Thanks all. – Mr Pain Oct 05 '22 at 12:43
  • @ths like confirm whether to go to the next page or stay in the same page, – Mr Pain Oct 05 '22 at 12:46
  • But it does what I want it to now tho, thanks – Mr Pain Oct 05 '22 at 12:47

1 Answers1

-2

Instead of alert, use confirm.

I created a wrapper called navigate that executes the callback, if the user hits the "OK" button.

The performNavigation event handler calls this wrapper function.

const navigate = (message, callback) => {
  if (confirm(message) && callback) {
    callback();
  }
}

const performNavigation = () =>
  navigate("Are you sure you want to proceed?", () => {
    console.log('Proceeding...');
  });

const button = document.querySelector('.collect');

button.addEventListener('click', performNavigation);
<button class="collect">Proceed</button>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132