-1

i want in seconds the background image in landing page changes automatically but it dosn't change and i don't know why and i wrote correctly the code and here is my path images img/img1.jpg, img/img2.jpg, and so on

<div class="landing-page">
    <div class="overlay"></div>
    
    <div class="header-area">
        <div class="logo">
            special design
        </div>
        <ul class="links">
            <li><a href="#" class="active">About</a> </li>
            <li><a href="#">Service</a> </li>
            <li><a href="#">Products</a> </li>
            <li><a href="#">contact</a> </li>
        </ul>
    </div>

    <div class="introduction-text">
        <h1>We Are <span class="main-color">Creative Agency</span></h1>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Atque et quidem nostrum tempore ab delectus totam in ducimus! Quae amet corrupti magni et. Adipisci officia at ipsum iste accusantium ullam!</p>
    </div>
</div>

my javascript code page

var myBackground  = document.getElementsByClassName('landing-page');

var myImages =[
    'img1.jpg',
    'img2.jpg',
    'img3.jpg',
    'img4.jpg',
];

myRandomNumber = Math.floor(Math.random() * myImages.length); 
console.log(myRandomNumber);

setInterval(() => {
    var randomNumber = myRandomNumber;

    myBackground.style.backgroundImage = 'url("img/' + myImages[myRandomNumber] + '")';
}, 1000);

changeImage(myBackground,myImages);
biberman
  • 5,606
  • 4
  • 11
  • 35
MEDO bro
  • 45
  • 5
  • 1
    Does this answer your question? [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – CBroe Sep 02 '21 at 10:23
  • The method `getElementsByClassName` returns an array, not an object. Therefore if you're sure "landing-page" is gonna be the only element with that class, you can access that element by adding index 0 before accessing it's properties: `myBackground[0].style....` P.s. The background image is only going to change once because the value of `myRandomNumber` does not change. (it only gets set once) – Mohi Sep 02 '21 at 10:24

1 Answers1

0

"use strict";
window.addEventListener('load', onLoaded, false);

var myImages = ['img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg'];

function onLoaded(event) {
  setInterval(
    () => {
      let tgtElem = document.querySelector('.loading-page');
      let randIndex = Math.floor(Math.random() * myImages.length);
      tgtElem.textContent = `img/${myImages[randIndex]}`;
      tgtElem.style.backgroundImage = `url("img/${myImages[randIndex]}")`;
    }, 1000
  );
}
header {
  background-color: #888;
  color: #ddd;
}
<header>
  <h1>title</h1>
</header>
<div class='loading-page'>
</div>
enhzflep
  • 12,927
  • 2
  • 32
  • 51