1

was trying to follow a guide that seemed to me very straightforward and simple that i found here:

Change css background-Image using javascript

however in my implementation it doesn't work. the image does not get displayed or changed. any hints?

EDIT: not the same as suggested duplicate. now that parenthesis after changeImage has been removed, the function gets repeated but the problem of not displaying any of the background images persists.

2ND EDIT: i also tried removing the parenthesis after buildImage, with the same result (no background images displayed)

<div id="pupa">

</div>

<script>


  var images = ['file:///Users/karin/PROJECTS/PORTFOLIO/pupal%20stage/img/stage12.jpg',
                'file:///Users/karin/PROJECTS/PORTFOLIO/pupal%20stage/img/stage34.jpg',
                'file:///Users/karin/PROJECTS/PORTFOLIO/pupal%20stage/img/stage56.jpg'];
  var index = 0;

  function buildImage() {
    console.log("setting image");
    document.getElementById('pupa').style.backgroundImage = 'url(' + images[index] + ')';
  }

  function changeImage() {
    index++;
    if (index >= images.length) index = 0;
    console.log("changing image");
    document.getElementById('pupa').style.backgroundImage = 'url(' + images[index] + ')';
  }

  buildImage();

  setInterval(changeImage, 3000);

</script>

пaean
  • 61
  • 8
  • 1
    Does this answer your question? [Why is the method executed immediately when I use setTimeout?](https://stackoverflow.com/questions/7137401/why-is-the-method-executed-immediately-when-i-use-settimeout) – Ivar Nov 25 '20 at 13:29
  • i tried removing parenthesis after changeImage, now that part is working :) thanks! however the images are still not displayed as background of the div (it has no background at all) – пaean Nov 25 '20 at 13:36
  • 2
    try changing `file:///Users/karin/PROJECTS/PORTFOLIO/pupal%20stage/img/stage12.jpg` to `img/stage12.jpg` (do that for each img). Paths must be relative to the `html` page or reachable absolute paths from the browser – firatozcevahir Nov 25 '20 at 13:46
  • Might indeed be an issue with local images. It should work fine: https://jsfiddle.net/6dg3o1fx/ – Ivar Nov 25 '20 at 13:47
  • firatozcevahir, this was my original solution but it did not work, that's why i changed it to the full path – пaean Nov 25 '20 at 13:55
  • Ivar, how do you mean? that the path is wrong? using the path 'img/stage12.jpg' doesn't work either – пaean Nov 25 '20 at 13:56
  • @firatozcevahir I guess that is the issue, because the code is working for me when using relative path. I guess the browser won't allow you to access files from your pc, due to security issues. And also check whether you have css set to display image, like `height, width, background-size` etc. And also note that you have set time delay to 3000 (3 seconds) which actually takes 3 seconds to set the first image, so it is also needed to set a default image by css or js. – 27px Nov 25 '20 at 13:57
  • @mponny well, do you see image load errors on console? If not, try setting some `width` `height` properties to your div's style. Because it looks like your div is not visible since it has no `height/width` properties set – firatozcevahir Nov 25 '20 at 13:57
  • @mponny it will be great if you could show the folder structure (path of html and files) and full code including css. – 27px Nov 25 '20 at 13:58
  • i don't see any image load errors. the width and height of the div are set to 100%, the background-size set to cover. i can access files fine from my browser (for instance, i can open the folder img and click on the images and that works) and have made html files locally that had no problem displaying images. also with javascript. i think the 3000 means 3000 milliseconds, that is 3 seconds, not 3 minutes. either way the first image at least should be displayed, since there is no delay for this one – пaean Nov 25 '20 at 14:04
  • @mponny Try the 3 images I used [here](https://jsfiddle.net/6dg3o1fx/) and see if those work for you. If they do, then it indeed seems not possible to use locally stored images. – Ivar Nov 25 '20 at 14:05
  • folder structure: index.htm and style.css are placed in the same folder, in this there is a folder called img that contains the images. here is the css for the div: – пaean Nov 25 '20 at 14:05
  • #pupa { padding: 0; margin: 0; top: 0; left: 0; width: 100%; height: 100%; background-size: cover; } – пaean Nov 25 '20 at 14:05
  • @Ivar what i see is grey rectangles with text "Image 1", "Image 2", "Image 3" – пaean Nov 25 '20 at 14:06
  • @mponny Then that's your issue. Either host those images online, or use a local webserver to serve them through it. – Ivar Nov 25 '20 at 14:08
  • @Ivar i tried linking to this image of an apple instead and it doesn't work either: https://i5.walmartimages.ca/images/Enlarge/094/514/6000200094514.jpg – пaean Nov 25 '20 at 14:11
  • @firatozcevahir i am using mac, the path is correct – пaean Nov 25 '20 at 14:13
  • @mponny You can't always use any image on the net. There are several ways to prevent [hotlinking](https://en.wikipedia.org/wiki/Inline_linking), which seems the case here. – Ivar Nov 25 '20 at 14:17
  • If you are using Safari, check this page https://stackoverflow.com/questions/17341728/background-image-not-showing-in-safari – firatozcevahir Nov 25 '20 at 14:19
  • @firatozcevahir seems like the only thing wrong was i set the div width/height to 100% instead of 100vw/vh. it's always some small mundane detail! had no idea the percentage could mess up the whole thing – пaean Nov 25 '20 at 16:43

1 Answers1

0

This code will work if you add your images in a folder called img in the same folder where the html page is.

<html>
  <head>
    <style>
      #pupa
      {
        width:300px;
        height:300px;
        background-position:center;
        background-repeat:no-repeat;
        background-size:cover;
      }
    </style>
  </head>
  <body>
    <div id="pupa"></div>
    <script>
      var images = ['img/stage12.jpg',
                    'img/stage34.jpg',
                    'img/stage56.jpg'];
      var index = 0;
      document.getElementById('pupa').style.backgroundImage = `url(${images[index]})`;
      setInterval(function(){
        index=(++index >= images.length)?0:index;
        console.log(`changing image of index : ${index}`);
        document.getElementById('pupa').style.backgroundImage = `url(${images[index]})`;
      },3000);
    </script>
  </body>
</html>

This is the same code tweaked a bit, and you don't need another function buildImage() to set image first, it works (make sure to check path of images)

Make sure to change width, height, background-size, image name, path etc according to your need.

27px
  • 430
  • 5
  • 16