Confirm cancel button not stopping the code execution with an anchor tag

I want the code execution to stop when No button is clicked but it seems to be moving with the href link even after clicking on No button. Am I doing something wrong here?

Here’s my JSFiddle

You need to use preventDefault. (I could have SWORN there was a thread about this exact thing within the past two days but can’t find it) :frowning:

I changed this over to more modern techniques just for simplicity sake.

Your link changes to this (click directive removed)

<a href="somepage.htm" class="urlLink" title="Activate"> Activate </a>

javascript changes to this:

// find all links with this class, add the checkType method to the click event
const link = document.querySelectorAll(".urlLink");
link.forEach((element) => { element.addEventListener("click", checkType, false);});

function checkType(evt){    // added evt here

   let realFunctionReturn = false;

   if (confirm('Ok or NO?')) {
	evt.preventDefault();  // added this here to prevent link from working ONLY if OK is clicked
	// Save it!
	console.log('Ok button clicked!');

    realFunctionReturn = true;
} else {
    // Do nothing!  Notice how the prevent default is NOT used here, so the link works....
   console.log('No button cicked');
   realFunctionReturn = false;

Thanks. I did onclick="return checkType()" in my anchor tag and it seems to be working. I like the different way that you suggested.

Separate question - is there a way to display Yes instead of Ok and Cancel instead of No buttons?

No because it’s window’s functionality. If you want to have a yes/no option, you’re going to need to go to more of a dialog option, which will be more work as you’ll not only have to capture the link, you’ll also be coding for extra buttons. This article gives you the bones of what you’re looking for.

Personally, I’d reverse your thought process to be clicking OK goes to the external link, and cancel stays there, then change the message to something like “Do you really want to leave this site? Click OK to leave or Cancel to stay”

Far less work and uses default functionality…

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.