Question

I have the following href on my site:

a href="http://www.google.com" name="external" onclick="confirmExit(this.name)

I just can't figure out how to make user stay on my website if he/she doesn't want to leave by clicking "cancel" (incomplete code below).

function confirmExit(name){
    if(name == "external"){
        if(confirm("Go to external site?")){

        }
    }
}

jQuery/Ajax is not an option.

Was it helpful?

Solution

Just return false.

function confirmExit(name){
    if(name == "external"){
        if(!confirm("Go to external site?")){
            return false;
        }
    }
}

If you want this to happen on all links, or even when the user closes the tab, check out @megawac's answer.

OTHER TIPS

Use window.onbeforeunload to show a confirm dialog before a user leaves the page

$(window).bind("beforeunload", function() {
   if(true) { //display confirm dialog?
       return "Are you sure you want to leave?";
   }
});

You don't need a function. I suggest you to use this:

$(function () {
     $('a[name="external"]').click(function () {
         if (!confirm("Go to external site?")) {
            event.preventDefault();
         }
     });
});

If you use this, you don't need to add onclick="confirmExit(this.name)" to everything. Just add the above and your work will be done.

You can do this if you want behaviour of JSFiddle:

window.onbeforeunload = function(){ return "Are you sure you want to leave the page?"; }

Use the return false inside the confirmExit() function and also use return at inline javascript like

HTML

<a href="http://www.google.com" name="external" onclick="return confirmExit(this.name)">Some Link</a>
                                  //Use return here also ---^

JS

function confirmExit(name){
    if(name == "external"){
        if(!confirm("Go to external site?")){
            return false;
        }
    }
}

DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top