Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prompt user for confirmation when clicking a link

I have a link that does some potentially dangerous function (delete something). I want to prompt user if he really wants to do it. I want to do it with javascript and it should be very simple.

My solutions so far:

<a href='/delete' onclick='return confirm("Are you sure?")'>delete</a>

.. is bad in a way that it is not triggered by middle click in Firefox and IE.

<a href='/delete' onmousedown='return confirm("Are you sure?")'>delete</a>

.. does not work. Even if true is returned on clicking Ok, link is not navigated.

What is the correct way to implement this?

like image 868
Josef Sábl Avatar asked Jun 29 '11 09:06

Josef Sábl


2 Answers

<a href='#' onclick='confirmUser()'>delete</a>

javascript

 function confirmUser(){
    var ask=confirm("Are you sure");
    if(ask){
      window.location="/delete";
     }
}
like image 196
Anupam Avatar answered Oct 31 '22 10:10

Anupam


I just solved this problem for an online banking client. FDIC requires a confirmation "speedbump" whenever the user is navigating to a third party site. We wanted to do it unobtrusively, and make it impossible to get around.

I've tested this with IE, Firefox, Chrome, and Android-- click, right click, middle click, shift click, shift F10, enter, long tap, everything (Firefox is the hard one). Either you get the speedbump or you get a blank tab, you can't get around it.

document.ready = function() {

    var handleSpeedBump = function(e) {
        e.preventDefault();

        var href = this.getAttribute("data-href");
        var sure = confirm("Are you sure you want to navigate to " + href + "?  This is a third party site and not owned by this institution.");
        if (!sure) return;
        document.location = href;
    }

    $("a.speedbump")
        .click(handleSpeedBump)
        .bind("contextmenu", handleSpeedBump)
        .dblclick(handleSpeedBump)
        .each(function() {
            var href = this.href;
            this.setAttribute("data-href", href);
            this.href = "javascript:void('Navigate to " + href.replace("'", "") + "')";
        })
}

To make this work, just write your link per normal and add "speedbump" to its classes.

<A href="www.thirdpartysite.com" class="speedbump">Here is the link!</A>
like image 41
John Wu Avatar answered Oct 31 '22 11:10

John Wu