Reputation: 8467
I am trying to express what I understood from reading some articles about dom0 event model in JavaScript. If there is a mistake in it, please correct me.
In dom0 model, an event handler can be attached to an element. Only one handler can be attached. When the event occurs, the browser calls that event handler.
There are two ways of doing this:
1.Inline model
The handler is added as an attribute of the element.For example a link element (i.e. <a>
) has an attribute called onclick
. We add a function hello
like this:
<a href="#" onclick="hello();"> say hello </a>
...
<script type="text/javascript">
function hello(){
window.alert("Hello");
}
</script>
The problem with this model is that it is intrusive, since the hello()
is put in the body of the element.
2.traditional model
Instead of adding event handler as attribute of element in the body of the element,the adding/removing of handler is done by script. The handler is assigned to the element's property as below:
<a href="#" id="hellolink"> say hello </a>
...
<script type="text/javascript">
function hello(){
window.alert("Hello");
}
//adding handler
document.getElementById('hellolink').onclick=hello;
</script>
Upvotes: 0
Views: 2433
Reputation: 405
Seems about right.
You might want to read: http://www.cross-browser.com/talk/event_interface_soup.php http://en.wikipedia.org/wiki/DOM_events#Traditional_model
and for the code in the traditional model you should have a a window.onload event
so
window.onload = function () {
var el = document.getElementById('hellolink');
if (el) {
el.onclick = hello;
}
};
depending on what browser you are using function hello might receive the element object, so maybe it'll easier for you if you use something like jQuery to handle your dom events.
Upvotes: 2