Home > Software design >  The js changing backgrounds function isn't working
The js changing backgrounds function isn't working

Time:01-03

Imma trying to create a simple function that change the background of a specific element when the user clicks it


const chrollofunction = document.querySelectorAll("article .krolor");

const randomclickfunctionkro = function() {

    const backgrounds = new Array();
    backgrounds[0] = new Image();
    backgrounds[0].src = 'pics/اليكيورا.jpg';

    backgrounds[1] = new Image();
    backgrounds[1].src = 'pics/pain.jpg';

    backgrounds[2] = new Image();
    backgrounds[2].src = 'pics/قزم2.jpg';

    const randomindex = Math.floor(Math.random() * backgrounds.length);

    const randombg = backgrounds[randomindex];
    
    chrollofunction.style.backgroundColor = randombg;
    console.log('The user clicked and changed the color to '   randombg);

};

chrollofunction.onclick = randomclickfunctionkro;

So i guess that there was a problem with the backgrounds function array , But i can't really understand it and I looked for how it should be written and the correct syntax but can't find any problem really

CodePudding user response:

You can change the background image of an element like so:

 chrollofunction.style.backgroundImage = `url(${randombg.src})`;

You may also need to add a few styles to make the image fit the container:

chrollofunction.style.backgroundSize = "contain";
chrollofunction.style.backgroundRepeat = "no-repeat";
  • Related