Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change image size with JavaScript

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?

like image 964
Spyderfusion02 Avatar asked Aug 19 '09 01:08

Spyderfusion02


People also ask

Can you change an images size using JavaScript?

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

How do I make an image smaller in JavaScript?

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.

How do I change the size of an image in HTML?

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.

How do you change an image in JavaScript?

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.


1 Answers

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!"/> 
like image 52
Pat Avatar answered Oct 02 '22 02:10

Pat