In HTML, we can click on an image to enlarge it with the help of the JavaScript getElementById() method and by targeting the width and height properties of the image.
The best way to show this is with an example.
Let’s say we have the following HTML:
If we want to enlarge the image to be double its width and height, we can use the getElementById() method to target the image and then change its width and height properties in the following JavaScript code.
var theImage = document.getElementById("image1");
theImage.width = theImage.width * 2;
theImage.height = theImage.height * 2;
When clicking on the image, the image will now double in size.
Note this can also be done in jQuery using the jQuery css() method.
Let’s see this example in action.
Clicking on an Image to Enlarge It Using JavaScript
In this example, we will have an image that we will want to enlarge. The image will have a width of 150px and a height of 150px.
Here is the simple HTML code for this example:
We will use an onclick event to run the function “enlargeImg()” when the user clicks the image.
We can then use the getElementById() method to target the width and height properties of the image and use it to enlarge our image.
We can take our code from the example in the above section and put it into our function called enlargeImg().
Below is the JavaScript code which will allow the user to be able to double the size of the image:
function enlargeImg(){
var theImage = document.getElementById("image1");
theImage.width = theImage.width * 2;
theImage.height = theImage.height * 2;
};
The final code and output for this example on clicking on an image to enlarge it in HTML is below:
Code Output:
Full Code:
Hopefully this article has been useful for you to understand how to in HTML, click on an image to enlarge it.