views:

43

answers:

2

This may seem a strange question, but please bare with me. I'm working through some javascript examples, and I just did this one:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>Page title</title>
<script type="text/javascript">
function displayText()
{
document.getElementById('targetDIV').innerHTML =  "You're using Javascript";
}
</script>

</head>
<body onload="displayText()">
<h2>This should be before the other text.</h2>

<div id="targetDIV">
</div>

</body>
</html>

OK. Very basic, I know-but I realized I was confused about the "why" of some things. Could it be accurate to say that:

Function=WHAT will happen.

The call (the body onload...)= WHEN it will happen.

and div id="targetDIV" = WHERE it will happen

I know this is the case in this example, but in general is that the way things work in Javascript?

Thanks! Joel

+1  A: 

Sound good to me.

Dhana
+4  A: 

Yes, that's a pretty good working model to carry in your head.

onload for the body is called an Event and many objects issue events. Your function displayText is called in response to the onload Event and is therefore an event handler.

The code inside your function can do anything, but in this case it dynamically loads some text into a tag on your page.

There are a couple of other things worth pointing out at this point. You access the tag using document.getElementById. document is variable available to you in Javascript which contains a model of the page called the DOM or document object model. This is extremely powerful as it presents a hierarchical layout of everything on your page and allows you to manipulate the contents.

getElementById() is a very useful function which searches the DOM tree and returns the object which has the ID that you specify, it's a sort of search. The text gets to your tag because you added the targetDIV id to the DIV tag and therefore you could find it via the DOM function.

Welcome to programming in Javascript. Now you have a goood working model you'll find loads of really clever things you can do and your life as a web programmer will never be the same again.

Simon