How to display a confirmation dialog when clicking an <a> link?

05/16/2020 15:00:02

I want this link to have a JavaScript dialog that asks the user “Are you sure? Y/N”.

<a href="delete.php?id=22">Link</a>

If the user clicks “Yes”, the link should load, if “No” nothing will happen.

I know how to do that in forms, using onclick running a function that returns true or false. But how do I do this with an <a> link?

Verified Answer (581 Votes)

05/05/2012 19:38:27

Inline event handler

In the most simple way, you can use the confirm() function in an inline onclick handler.

<a href="delete.php?id=22" onclick="return confirm('Are you sure?')">Link</a>

Advanced event handling

But normally you would like to separate your HTML and Javascript, so I suggest you don't use inline event handlers, but put a class on your link and add an event listener to it.

<a href="delete.php?id=22" class="confirmation">Link</a>
<script type="text/javascript">
    var elems = document.getElementsByClassName('confirmation');
    var confirmIt = function (e) {
        if (!confirm('Are you sure?')) e.preventDefault();
    for (var i = 0, l = elems.length; i < l; i++) {
        elems[i].addEventListener('click', confirmIt, false);

This example will only work in modern browsers (for older IEs you can use attachEvent(), returnValue and provide an implementation for getElementsByClassName() or use a library like jQuery that will help with cross-browser issues). You can read more about this advanced event handling method on MDN.


I'd like to stay far away from being considered a jQuery fanboy, but DOM manipulation and event handling are two areas where it helps the most with browser differences. Just for fun, here is how this would look with jQuery:

<a href="delete.php?id=22" class="confirmation">Link</a>
<!-- Include jQuery - see -->
<script type="text/javascript">
    $('.confirmation').on('click', function () {
        return confirm('Are you sure?');

Answer #2 (14 Votes)

05/05/2012 19:38:59
<a href="delete.php?id=22" onclick = "if (! confirm('Continue?')) { return false; }">Confirm OK, then goto URL (uses onclick())</a>

Answer #3 (5 Votes)

07/19/2017 10:28:10

You can also try this:

<a href="" onclick="if (confirm('Delete selected item?')){return true;}else{event.stopPropagation(); event.preventDefault();};" title="Link Title">
    Link Text
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.