Skip to content Skip to sidebar Skip to footer

Using The Confirm Method When Leaving Site

I want a confirm message to popup when clicking on an external link. Though it doesnt want to work out. I dont get the confirm popup when i click on an external link. Any solutions

Solution 1:

This behavior can only be accomplished by handling the onbeforeunload event. Your handler should return a string, which is the message that appears to the user. A simple example:

window.onbeforeunload = function () {
    return'are you sure you want to leave?';  
};

http://jsfiddle.net/rHkfM/

Solution 2:

May I suggest to slightly modify your code:

functioninit() {
    var warn = document.getElementsByTagName("ul");
    for(i=0; i<warn.length; i++)
        if(warn[i].className == "meny"){
            var link = document.getElementsByTagName("li");
    }
    var links = document.getElementsByTagName("a");
    for(i=0; i<link.length; i++){
        if(links[i].className == "external"){
            links.external = true;
        }
    }
}

then add:

window.onbeforeunload = function (event) {
    if (event.srcElement.external)
        return'are you sure you want to leave?';  
};

Please pay attention, this line:

var links = document.getElementsByTagName("a");

must be outside the loop.

Post a Comment for "Using The Confirm Method When Leaving Site"