How to display a confirmation dialog when clicking a link with JavaScript?

Spread the love

Sometimes, we want to display a confirmation dialog when clicking a link with JavaScript.

In this article, we’ll look at how to display a confirmation dialog when clicking a link with JavaScript.

How to display a confirmation dialog when clicking a link with JavaScript?

To display a confirmation dialog when clicking a link with JavaScript, we can add a click listener to the body.

For instance, we write

const reallySure = (event) => {
  const message = "Are you sure about that?";
  const action = confirm(message) ? true : event.preventDefault();
};

const actionToFunction = (event) => {
  switch (event.target.tagName.toLowerCase()) {
    case "a":
      reallySure(event);
      break;
    default:
      break;
  }
};

document.body.addEventListener("click", actionToFunction);

to call document.body.addEventListener to add the actionToFunction click listener to it.

In it, we check if the element clicked is an a element with event.target.tagName.toLowerCase().

If it’s 'a', then we call reallySure with event.

In reallySure, we call confirm to show a confirm message.

And we call event.preventDefault if it returns false.

Conclusion

To display a confirmation dialog when clicking a link with JavaScript, we can add a click listener to the body.

Leave a Reply

Your email address will not be published.