- slide 1 of 3
The HTML onClick Event Handler
- slide 2 of 3
Examples of HTML onClick Event Handler
Let us go through simple examples so that you get the basic idea of what onClick event handler is and how it is used.
1) Copy the following code and use a text editor like notepad and save it in any name but with the .html extension. For example I have saved the file as onclick.html.
<a href="#" onClick="alert('You just Clicked!')";>Click Here.</a>
In the above example I have not used any script in the head section. In the body section I have created a link and associated an onClick event that will fire an alert when the link is clicked. Thus an onclick event is executed.
In this example let us change the text when the user clicks the part of the text that has an onClick event associated with it.
<h1>Click me and I will not change.</h1>
<h1 onClick="this.innerHTML='There! I changed.'">Click me and I will change.</h1>
<h1 onClick="window.location='http://www.google.com'">Click me and I will change.</h1>
In the above example the user is sent to another webpage using the onClick event handler that has been associated to it.
It is just that easy to use the onClick event handler. The onClick event can get complex but this article is targeted to those who want to understand the basics of the onClick event handler and only simple examples are used for their understanding.
- slide 3 of 3
When and Where Should onClick Events in HTML are Used:
The best use of onClick events are seen in:
1) Forms: When the user submits a form, an onClick event is executed when the Submit button of the form is clicked. When the submit button is clicked an onClick event is fired to see if the all the data in the form is appropriate. If the data entered in the form abides by all the rules the window.location object is executed so that the user is sent to another page. If the data entered in the form doesn't abide by certain rules, the form is shown to the user so that he can enter appropriate data.
2) To show hidden data,
3) To change data,
4) To alert the user when he clicks certain objects.
The uses are many and it is upto the developer to use the onClick event handler as per his requirements.
Even efficient and great programmers tend to make some silly and careless mistakes. Here are that mistakes that you should avoid when you use the onClick() event handler.
1) Although no error will be shown it is always good to use onClick with the capital C.
2) Don't associate more than one onClick event to an object as it will lead to a logical error.