...

View Full Version : Confirm box on clicking link with HTML class "external"



zhouhana
12-20-2011, 07:06 PM
Hey guys,

This is my first time ever posting in a programming forum so please be nice! :)

I'll admit right away that this is for a homework assignment, but I really did try to solve it myself before I decided to post here. The instructions are to have a confirm box pop up when links with the HTML class value "external" are clicked. If the user clicks "OK" they should be directed to the linked page. If they click "Cancel" they should not be directed anywhere.

Here's my code:



function checkClass() {
var links = document.getElementsByTagName("a");
for ( var i = 0 ; i < links.length ; i++ ) {
var link = links[i];
if (link.className == "external") {
link.onclick = clickHandler();
}
}
}

window.onload = checkClass;

function clickHandler() {
if (confirm("You clicked an external link. Do you really want to leave this site?")) {
return true;
}
return false;
}


The problem is that the confirm box is triggered on page load and not on link click. I know I wrote
window.onload = checkClass; but how else should I call the function? I thought
if (link.className == "external") would keep it from going as far as to the confirm box until an external link was clicked.

Thanks for pointing me in the right direction,

Johanna

xelawho
12-20-2011, 07:23 PM
it can be simplified more, but you can change that line to

link.onclick = clickHandler;

to prevent the function from getting called immediately

Dormilich
12-21-2011, 04:39 PM
the other point is, returning false doesn’t stop the link from redirecting. you explicitly need to stop that using Event.preventDefault().


function stopAction(evt)
{
// for IE < 9
evt = evt || window.event;
// prevent default action
evt.preventDefault();
// again for IE < 9
evt.returnValue = false;
}

zhouhana
12-21-2011, 06:36 PM
Thanks, xelawho, that did the trick!

Dormilich, is that an IE problem? In Firefox my code works as expected after xelawho's improvement.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum