In this tutorial we will learn How to Change Image Size with JavaScript. For this we can use JavaScript style property with which we can change both height and width of the image.
Table of Contents
style property
style property returns the CSSStyleDeclaration object which contains all CSS inline properties of an HTML element.
In this example it is used to change the size of img tag.
HTML Code
HTML Code is given below, in this code we have img tag and a button tag with onclick event which is used to execute a JavaScript function.
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Change image Size</title>
<style>
.responsive
{
width: 100%;
}
</style>
</head>
<body>
<img src="car.jpg" id="image" class="responsive">
<button onclick='changeImageSize()'>Change Image Size</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, in this code getElementById() method is used to select or target the image.
In the end style property changes the size of image.
<script>
function changeImageSize()
{
var image = document.getElementById('image');
image.style.height ='100px';
image.style.width = '200px;'
}
</script>
We can also change only height or width of the image.
<script>
function changeImageSize()
{
var image = document.getElementById('image');
image.style.width = '200px;'
}
</script>
Demo
Video Tutorial
Watch video tutorial on How to change Image size with JavaScript.