[SOLVED] How to set image width and height using javascript?

Issue

This Content is from Stack Overflow. Question asked by fullstackgenerator

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 class="containter-fluid">
        <div class="row">
                <div class="text">
                some text
                </div>
            </div>
        </div>



Solution

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


This Question was asked in StackOverflow by fullstackgenerator and Answered by Gavri Ramlik It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?