Javascript- Onclick Event Handler


The Onclick event handler in Javascript is an event handler that executes when a user clicks on a web element.

This web element can be anything, such as a button, an image, a header, or any other various HTML element.

Thus, when the element is clicked that has a onclick event handler attached to it, the onclick triggers whatever action the programmer designed to occur when this event takes place.

For example, the image below converts from a rock to a tree when clicked upon. Try it:

Click on the rock below to change it to a tree:


To create this image above that changes to another image when clicked on, we assign an onclick event handler to the image.

The full HTML code is:

<img id="image" onclick="changeimage()" src="/images/Rock.png">

Here in the HTML code, we assign an id of image to the image tag. We then add our onclick event handler to the image tag. This event handler calls the changeimage() function which we create in a Javascript script, which below. This function changes the image from the rock to tree.

Javascript Code

The coding of the changeimage() function is:

function changeimage()
document.getElementById("image").src= "/images/nature.png";

This script accesses the image which wants to be changed through the id tag. Being that we gave the image in HTML an id of image, we use the following line to access that image through the id and change the src attribute to the image src attribute of the new image.

Second Example

Now for a second example, we attach the onclick event handler to a button. When the button is pressed, the size of the image decreases. aptera

The HTML code of the original element is:

<img id="imagesize" width="871px" height="307px" alt="aptera" src="/images/car.png">

<button onclick="changeimagesize()">Make Image Smaller</button>

So the button has an onclick event handler which calls the changeimagesize() function. This function decreases the height and size dimensions of the aptera car image.

Javascript Code

The Javascript code to create the changeimagesize() function:

function changeimagesize()
document.getElementById("imagesize").width= 534;

We then put this in a function so that the button will call this function when clicked.

This example demonstrates the onclick event handler attached to a button.

Related Resources

Javascript- Onload Event Handler

Javascript- Onunload Event Handler

Javascript- Onfocus Event Handler

Javascript- Onblur Event Handler

Javascript- Onchange Event Handler

Javascript- Onkeydown Event Handler

Javascript- Onkeyup Event Handler

Javascript- Onmouseover Event Handler

Javascript- Onmousedown Event Handler

Javascript- Onmouseup Event Handler

Javascript- Onmouseout Event Handler

Javascript- Onreset Event Handler

Javascript- Onabort Event Handler

Javascript- Oncopy Event Handler

HTML Comment Box is loading comments...