Applying events to HTML or XHTML web page elements can be done by setting event properties directly in the tag code or by using the DOM and some JavaScript code.The area of least compliance between browsers and the DOM is the event object model, yet events can be set as a property of the element.
Intro
The area of least compliance between browsers and the Document Object Model (DOM) is the event object model. But we can apply events to web elements as we would a property - such as onclick=“some action…” . We can do this by setting the onclick attribute in the tag code or through JavaScript. Setting an event action is more powerful and flexible if done through a script as we’ll see in the following examples. The tag format used in this article is XHTML but the same holds true for HTML .
Set the OnClick Event in the Tag Code
The code below shows a div and button element. Clicking the button (firing the button’s onlick event) will change the innerHTML of the div element from “Click the button below” to “You clicked!”. We’re applying the getElementById(tagID) DOM method to set the button’s onclick attribute / property, right in the tag definition.
Code view
Set the OnClick Event by JavaScript
The source code is the same as in the previous example except for setting the button’s onclick property by calling or referencing a JavaScript function.
Case 1: By calling a named function object
Here the function “doSomething” is a function object that does not return a result but performs an action; it changes the content of the div whose id is “messageDiv”. So if the onclick event of the button is set to “doSomething()”, the function is immediately executed when the user clicks the button.
Code view
Case 2: By calling an object whose type is an anonymous function
In this case, doSomething is a javascript object whose type is an anonymous function and constructor is the code to the right of the equal sign. A document.writeln(doSomething) will write out the constructor of doSomething as a string; “function (){ document.getElementById(‘messageDiv’).innerHTML=‘You clicked!’ ;}”.
To execute doSomething, include the left and right parenthesis; “doSomething()”.
Code view