onClick Event handler

Ok, lets see how the onclick event-handler can help us. Remember, any event handlers are added inside html tags, not inside <script></script> ( there is an alternate way, which will not be discussed in this section). First of all, does that mean we can add event handlers inside any html tag? Noooo! In the case of the" onClick" event handler, which executes a piece of JavaScript when an element is clicked on, it can only be added to visible elements on the page such as <a>, form buttons, check boxes, a DIV etc. You wouldn't expect to be able to add this event handler inside the <head> tag for example, and you can't. With that understanding, lets see an example:

Click here for output:
function inform(){
	alert("You have activated me by clicking the grey button! Note that the event handler is added within the event that it handles, in this case, the form button event tag")

<input type="button" name="test" value="Click me" onclick="inform()">

The function inform() is invoked when the user clicks the button.

Ok, let me show you another example that adds the onclick event inside form radio buttons:

Try this: (it will change the background color of a document interactively)

<form name="go">
<input type="radio" name="C1" onclick="document.bgColor='lightblue'">
<input type="radio" name="C2" onclick="document.bgColor='lightyellow'">
input type="radio" name="C3" onclick="document.bgColor='lightgreen'">

I've put the actual demo of this example onto another window. Click the button to see it.

Click here for output:

I used the onclick handler to change the background color. Notice that we just wrote in plain English the name of the can do that, for most colors, or for a greater selection, use its hex value (ie: #000000).

Follow Us
Facebook Fan Page