...

View Full Version : simple alert not working!



byte1bit
02-17-2007, 12:06 PM
could someone please tell me why this simple code is not working? :eek: i tried all variation i could remember, i click and click, tried in firefox IE, netscape, and nothing:

<html>
<head>
<title>behavior</title>
<script language="javascript" type="text/javascript">
var parag = document.getElementsByTagName("p");
for(var i=0; i<parag.length; i++) {
parag[i].onclick = function() {
alert("click!");
}
}
</script>
</head>
<body>
<p>one paragraph</p>
<p>other paragraph</p>
</body>
</html>

any kind of help wuld ge appreciated.

BonRouge
02-17-2007, 03:47 PM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
* {
margin:0;
padding:0;
}
body {
background-color:white;
}
</style>
<script type="text/javascript">
function click() {
var parag = document.getElementsByTagName("p");
for( i=0; i<parag.length; i++) {
parag[i].onclick = function() {
alert("click!");
}
}
}
window.onload=click;
</script>
</head>
<body>
<p>one paragraph</p>
<p>other paragraph</p>

</body>
</html>

Kor
02-17-2007, 04:40 PM
...and the reason is:

The loading process works sequentially (well, not exactly, but to simplify it for your problem, let's say it does so). So that the moment you try to find the element (with javascript placed in head), that element is not yet loaded (in the body)

Most of the time javascript uses functions called by an event, following an user's action. The user's action is, in your case loading the page. For this action javascript uses window.onload event. By short onload

byte1bit
02-18-2007, 01:16 PM
you are right. i think that is why calling the function with

<script>
function click(){}
window.onload=click();
</script>

doesn't work and

<body onLoad="click();">

does work. thanks



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum