How to Create an Are You Sure? Alert with JavaScript onClick?

Estimated read time 2 min read

To create an “Are You Sure?” alert with JavaScript onClick, you can attach an event listener to the element you want to trigger the alert, such as a button or a link. Here’s an example code snippet that demonstrates how to create an “Are You Sure?” alert with JavaScript onClick:

<button onClick="confirmAction()">Delete</button>

<script>
function confirmAction() {
  const result = confirm("Are you sure you want to delete?");
  if (result) {
    // Perform the action if the user clicked "OK"
    console.log("Action confirmed");
  } else {
    // Do nothing if the user clicked "Cancel"
    console.log("Action canceled");
  }
}
</script>

In this code, a button element is created with an onClick attribute set to the confirmAction() function.

Inside the function, the confirm() method is called with a string message to display the “Are you sure you want to delete?” alert dialog with two buttons: “OK” and “Cancel”.

If the user clicks “OK”, the confirmAction() function logs “Action confirmed” to the console and performs the desired action. If the user clicks “Cancel”, the function logs “Action canceled” to the console and does nothing.

You can replace the console logs with your own custom code to perform the desired action or display a different message to the user.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply