This post will discuss how to change the size of an image in JavaScript and jQuery.

1. Using JavaScript

In plain JavaScript, you can directly modify the CSS width and height property of the image.

The following example demonstrates this by altering the CSS width property by specifying the absolute value in pixels and leave the browser to calculate the corresponding height while maintaining the aspect ratio.

JS


HTML



Edit in JSFiddle

 
You can either provide an absolute value or value in percentage. The following example changes the size of an image relative to its original size.

JS


HTML



Edit in JSFiddle

 
Alternatively, you can directly modify the actual height and width attributes of the image.

JS


HTML



Edit in JSFiddle

2. Using jQuery

With jQuery, you can use the .css() method to set CSS width and height property.

jQuery


HTML



Edit in JSFiddle

 
The .css() method can also take a single object of key-value pairs. So, the code can be shortened to:

Edit in JSFiddle

 
Another plausible solution is to specify the width and height in a CSS class and apply that class to the image element. This can be easily done using the jQuery’s .addClass() method. To overwrite an existing class, don’t forget to include !important declarations.

jQuery


CSS


HTML



Edit in JSFiddle

That’s all about changing the size of an image in JavaScript and jQuery.