I'm trying to change the size of an image with JavaScript. The jS file is separate from the HTML page.
I want to set the height and width of an image in the JS file. Any good ways on doing this?
Using JavaScript In plain JavaScript, you can directly modify the CSS width and height property of the image.
Answer: Use the JavaScript width and height property You can use either width or height JavaScript property to proportionally increase and decrease the dimension of an image like zoom-in and zoom-out feature.
If your image doesn't fit the layout, you can resize it in the HTML. One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels.
You can use the image id and getElementById method to change or swap images by click on a button or itself on images in JavaScript.
Once you have a reference to your image, you can set its height and width like so:
var yourImg = document.getElementById('yourImgId'); if(yourImg && yourImg.style) { yourImg.style.height = '100px'; yourImg.style.width = '200px'; }
In the html, it would look like this:
<img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With