PDA

View Full Version : Redirect Links



pssparkman
07-02-2008, 09:33 PM
Is there a script or sorts that when a link, any link, on a page is clicked that it asks the user a if they want to continue to that page. If they click OK than they will continue to the page if not they click Cancel and they stay. A popup that will allow for a custom message.

Thanks

techietim
07-02-2008, 10:46 PM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Link Confirm</title>
<script type="text/javascript">
function confirmLinks(){
elements = document.getElementsByTagName("a");
for(i = 0; i <= elements.length - 1; i++)
elements[i].onclick = function() { return confirm("Are you sure you wish to leave this website?"); }
}
</script>
</head>
<body onload="confirmLinks()">
<p><a href="http://google.ca">Link 1</a></p>
<p><a href="http://php.net">Link 2</a></p>
</body>
</html>

jscheuer1
07-03-2008, 01:24 AM
It works, but XHTML isn't a good idea for the vast majority of pages, and certainly not required here. More importantly, you have exposed two undeclared global variables:

examples

and:

i

Add to that reliance upon getElementsByTagName when it is not required (limits the number of browsers the script will work on).

Your code does work and demonstrates cleverness, but please consider this version, which doesn't suffer from any of the issues I mentioned, and that works just as well:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Link Confirm</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function confirmLinks(){
for(var l = document.links, i = 0; i <= l.length - 1; i++)
l[i].onclick = function() { return confirm("Are you sure you wish to leave this website?"); }
}
</script>
</head>
<body onload="confirmLinks()">
<p><a href="http://google.ca">Link 1</a></p>
<p><a href="http://php.net">Link 2</a></p>
</body>
</html>