Home > Software engineering >  How to set image width and height using javascript?
How to set image width and height using javascript?

Time:09-19

I'm trying to adjust the following javascript code (found here ) so the background images will fit the screen. Currently they're streched too far down. I believe the problem is in the mobileImages.style.width, mobileImages.style.height desktopImages.width and desktopImages.height. Could somebody point out my mistake(s)?

function changeImg(imgNumber)   {
        var mobileImages =["images/1mini.png","images/2mini.png","images/3mini.png"]; 
        mobileImages.style.width = '100vw';
        mobileImages.style.height = 'auto';
            var desktopImages = ["images/desktop/1.jpg", "images/desktop/2.jpg", "images/desktop/3.jpg", "images/desktop/4.jpg", "images/desktop/5.jpg", "images/desktop/6.jpg", "images/desktop/7.jpg", "images/desktop/8.jpg", "images/desktop/9.jpg", "images/desktop/10.jpg", "images/desktop/11.jpg", "images/desktop/12.jpg", "images/desktop/13.jpg", "images/desktop/14.jpg", "images/desktop/15.jpg", "images/desktop/16.jpg", "images/desktop/17.jpg", "images/desktop/18.jpg", "images/desktop/19.jpg", "images/desktop/20.jpg", "images/desktop/21.jpg", "images/desktop/22.jpg", "images/desktop/23.jpg", "images/desktop/24.jpg", "images/desktop/25.jpg"];
        desktopImages.width = '100vw';
        desktopImages.height = 'auto';
            var imgShown = document.body.style.backgroundImage;

            //this code will return true when device is mobile
            if (navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(android)|(webOS)/i)) { 
                var newImgNumber =Math.floor(Math.random()*mobileImages.length);
                document.body.style.backgroundImage = 
                                  'url(' mobileImages[newImgNumber] ')';  
            }else{
               var newImgNumber =Math.floor(Math.random()*desktopImages.length);
               document.body.style.backgroundImage = 
                                  'url(' desktopImages[newImgNumber] ')';
            } 
        }


        window.onload=changeImg;
body, html {
    margin: auto;
    overflow: hidden;
    background-size: cover;
}
    <div >
        <div >
                <div >
                some text
                </div>
            </div>
        </div>

CodePudding user response:

u trying to apply width and height to array of images, u can set width and height only to dom nodes

CodePudding user response:

Take look in the example below. It will use inline style. But you can assign some styles in your css and bind them to the image by using javascript (classList -> https://developer.mozilla.org/en-US/docs/Web/API/Element/classList?retiredLocale=de).

const img = document.querySelector("img");
img.style.width = "200px"
img.style.height = "200px"
console.log(img)
<img src="https://placeimg.com/640/480/any">

CodePudding user response:

You're styling the array, which does nothing!

Example 1

We simply get the img element, then we style it as you tried.

let img = document.querySelector('.img');
img.style.width = '200px';
<img  src="https://www.w3schools.com/html/pic_trulli.jpg" />

Example 2

In this example, we append the imgs to the DOM first then we style it! and that's the point!

// Images src
let imgs = ['https://www.w3schools.com/html/img_chania.jpg', 
            'https://www.w3schools.com/html/img_girl.jpg'];

// Array to hold HTML output (images as elements)
let holder = [];

// Create elements based on src above and push it to the array (holder) 
imgs.forEach(img => {
    let el = `<img  src="${img}" />`;
    holder.push(el);
});

// Print the output of the holder to the DOM (HTML)
document.getElementById('wrapper').innerHTML = holder.join('');

// Get the images and set it's width
let images = document.querySelectorAll('.imgs');
images.forEach(img => {
    img.style.width = '200px';
});
<div id="wrapper"></div>

Example 3 (based on your code)

  1. First you didn't choose the index when you called the function.
  2. Remember, you have to style the background properties and NOT width and height! since it's not an img! It's a background-image!
  3. If the index is randomly picked, then no need for the parameter, get a random number and pass it as an index.

Background Properties:

  • background-image
  • background-position
  • background-size
  • background-repeat
  • background-origin
  • background-attachment

If it's an img then make sure it's in the DOM before you can style it.

MDN - background property

function changeImg(imgNumber)   {
  var desktopImages = [
      "https://www.w3schools.com/html/pic_trulli.jpg",
      "https://www.w3schools.com/html/img_girl.jpg"];
      
  document.body.style.backgroundImage = 'url('  desktopImages[imgNumber]  ')';
}


window.addEventListener("load", () => {
  changeImg(1)
});
body, html {
    margin: auto;
    overflow: hidden;
    background-size: cover;
}
<div >
  <div >
    <div >
    some text
    </div>
  </div>
</div>

  • Related