Categories
JavaScript Answers

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

Spread the love

To display a confirmation dialog when clicking an anchor link with JavaScript, we can call the confirm function in the click handler.

For instance, we write

const reallySure = (event) => {
  const message = "Are you sure about that?";
  const action = confirm(message);
  if (!action) {
    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 with 'click' to add the actionToFunction click handler to the body element.

In actionToFunction, we check if an a element is clicked by getting the tag name of the element clicked with event.target.tagName.

If 'a' is returned after converting it to lower case, then we call reallySure.

In it, we call confirm to check if the user wants to confirm the action.

And if the user cancels, we call preventDefault to stop the default click behavior.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *