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 ?
Javascript code
function warning(){
var warning = confirm('Do you want to leave');
if(!warning){
alert("Staying on site");
return false;
} else {
alert("Leaving site");
return true;
}
}
function init() {
var warn = document.getElementsByTagName("ul");
for(i=0; i<warn.length; i++)
if(warn[i].className == "meny"){
var link = document.getElementsByTagName("li");
}
for(i=0; i<link.length; i++){
var links = document.getElementsByTagName("a");
if(links[i].className == "external"){
links.onclick = warning;
}
}
}
Html code:
<ul class="meny"">
<li><a class="external" href="https://www.mah.se">Mah</a></li>
<li><a class="external" href="https://www.google.se/">Google</a></li>
<li><a class="external" href="http://www.facebook.com/">Facebook</a></li>
<li><a class="external" href="http://www.youtube.com/">Youtube</a></li>
<li><a href="#">Digitalt</a></li>
<li><a href="#">Kultur</a></li>
<li><a href="#">Nöje</a></li>
<li><a href="#">Sport</a></li>
<li><a href="#">Familj</a></li>
<li><a href="#">Resor</a></li>
<li><a href="#">Inrikes</a></li>
<li><a href="#">Utrikes</a></li>
<li><a href="#">Jobb</a></li>
</ul>
May I suggest to slightly modify your code:
then add:
Please pay attention, this line:
must be outside the loop.
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:http://jsfiddle.net/rHkfM/