Question

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?

Was it helpful?

Solution

warning.onclick = confirm('Do you want to leave');

This calls confirm() immediately, and assigns the result (either true or false) to onclick (which is meaningless).

Instead, you need to create an anonymous function that calls confirm() and returns the result.

OTHER TIPS

The above clearly won't work

Yes. There are countless errors in the code:

  • Your variable warning has the same name as the function - bad practise as this leads to confusion
  • warning.onclick won't work since getElementsByClassName returns a NodeList, and you can attach listeners only to single elements
  • = confirm('Do you want to leave'); directly assigns the result of calling confirm. You certainly wanted to assign a function that, it will get invoked when the event happens
  • if(warning) will always be true since even an empty NodeList is truthy
  • return false; alert() - the alert will never be executed. A return statement immediately jumps out of the function.

how do you do it?

Not at all. Popups that hinder the user doing what he wants to do (he wants to leave the site when he clicks the link) are undesirable. This is extremely bad UI design.

jQuery dialog would be perfect for this just add code

warning.onclick = function()
{
 var msg = "do you want to leave this site: ";

 $( "#dialog-confirm" ).html(msg);
 $( "#dialog-confirm" ).dialog({
resizable: false,
title: 'title',
height:300,
modal: true,
buttons: {
    "Ok": function() {
        $( this ).dialog( "close" );
        window.location.href = url;
        },
    "Cancel": function() {
        $( this ).dialog( "close" );
        }
    }
    });
   }

do this instead:

var boolOK = confirm('Do you want to leave');

if (boolOK == true)
warning.onclick;

more explanations here http://www.javascriptkit.com/javatutors/alert2.shtml

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