I am trying to use a confirm method for external links. When you press the link, the question is supposed to popup, asking you if you want to leave the site? Everything goes as planned, except that you leave the site regardless of which button you click.
function warning(){
var warning = document.getElementsByClassName("external");
warning.onclick = confirm('Do you want to leave');
if(warning){
alert("Leaving site");
}
else{
return false;
alert("Staying on site");
}
}
The above clearly won’t work, how do you do it?
This calls
confirm()immediately, and assigns the result (either true or false) toonclick(which is meaningless).Instead, you need to create an anonymous function that calls
confirm()and returns the result.