Forum Moderators: open
example of code
<SCRIPT LANGUAGE="JavaScript">
<!--
ns4 = (document.layers)? true:false
ie4 = (document.all)? true:false
function init() {
if (ns4) block = document.blockDiv
if (ie4) block = blockDiv.style
}
//-->
</SCRIPT><BODY onLoad="init()">
<A HREF="javascript:alert(block.left)">left</A> -
<A HREF="javascript:alert(block.top)">top</A>
<DIV ID="blockDiv" STYLE="position:absolute; left:50px; top:100px; background-color:red; layer-background-color:red;">
</DIV>
</BODY>
Let say if you don't have <div id="blockDIV"> then it will give you javascript error. how to get rid of error by ignoring the javascript script?
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
window.onerror = echo;
function echo(err) {
if(err) {
alert("The following JavaScript error occured:\n\n" + err);
return true;
}
}
</script>
</head>
<body>
<a href="javascript:blah()">Error 1</a>
<a href="javascript:alert('test)">Error 2</a>
<a href="javascript:echo()">No error</a>
</body>
</html>
You can customize the echo function to do whatever you want... Silently do nothing (= just return true) if you want, or whatever :)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<style type="text/css">
html,body{height:100%;}
</style>
<script type="text/javascript">
function ckId(){
if(document.getElementById("divOne"))alert(true);
if(!document.getElementById("divTwo"))alert(false);
if(document.getElementById("divThree"))alert("won't happen");
}
</script>
</head>
<body onclick="ckId();">
<div id="divOne"></div>
</body>
</html>
You can also just check for the presence of the <div>:if(document.getElementById('myDiv')) {
...
}
Oh, duh! Don't I feel stupid now :)
Rambo Tribble and BlobFisk are obviously right on the spot! However, if you still want to catch the error (or multiple errors)... ;)
[edited by: DrDoc at 3:14 pm (utc) on June 15, 2004]