We can use JavaScript to resize an image easily by targeting the Style width and height properties and using the getElementById() method.

document.getElementById("image1").style.width = "150px";

Let’s say we have the following HTML:

If we want to resize the image to be a set 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.

document.getElementById("image1").style.width = "150px";
document.getElementById("image1").style.height = "150px";

Note this can also be done in jQuery using the jQuery css() method.

Using JavaScript to Resize an Image with a Click

To resize an image using JavaScript, we can combine the getElementById() method with an onclick event.

In this example, we will have an image that we will want to resize. The image will be in a div that will have a width of 300px. The image will start at a width of 100% to fill the entire div.

We will have a button that will allow the user to resize the image to a new width each time they press it.

Here is our HTML code:

Resize image

We will use an onclick event to run the function “resizeImage” when the user clicks a button.

We can then use the getElementById() method to target the width property of the image and use it to resize our image.

In this example, when the user clicks to resize the image, we will generate a random number from 0-100, and then set the width to that percentage.

We will let the user see the new width of the image by populating the #result div with the new width percentage using the textContent property.

Below is the JavaScript code which will allow the user to be able to resize our image by a random percentage each time:

function resizeImage(){
  var random = Math.round(Math.random() * 100);
  var newWidth = random + "%";
  document.getElementById("image1").style.width = newWidth;
  document.getElementById("result").textContent = ("width: " + newWidth);
};

The final code and output for this example on resizing an image in jQuery is below:

Code Output:


Resize image

Full Code:

Resize image

Hopefully this article has been useful for you to understand how to use JavaScript to resize image.

Categorized in:

JavaScript,

Last Update: March 1, 2024