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.
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.
Case 2: By calling an object whose type is an anonymous function
To execute doSomething, include the left and right parenthesis; “doSomething()”.
Case 3: By referencing an object whose type is an anonymous function
The button’s onclick event is set by accessing it with the DOM getElementById(tagID) method and setting the onclick to doSomething . This assigns the doSomething object constructor to the button’s onclick attribute.
*Note With this technique, you can also change the onclick property after the button is clicked by using the this statement.
This post is part of the series: Web Design using DHTML and the DOM
Creating web sites with DHTML based on the DOM can increase server performance, lower bandiwdth utilization and solve most cross-browser compatibility issues.
- Validating Input at the Client: Check for blank or required fields
- Validating Input at the Client: trim the field
- Validating Input at the Client: check numeric value fields
- Leveraging CSS Styles
- DOM getElementsByTagName Method for Bulk Element Formating