0

I am making a slideshow in JS and am encountering an annoying error. I have looked on this site for solutions, but none work. Apologies if I missed anything.

<head>
    <script>
        var i = 0;
        var images = [];
        var time = 3000;
        images[0] = 'image0.jpg';
        images[1] = "image1.png";
        images[2] = "image2.png";
        images[3] = 'image3.PNG'
        function changeImg(){
            document.getElementById("slide").src = images[i];
            if(i < images.length-1){
                i++;
            }else{
                i = 0;
            }
            setTimeout("changeImg()",time);
        }
        window.onLoad = changeImg();
    </script>
    <link rel="stylesheet" href="style.css">
</head>

<img src = "image0.jpg" id = "slide" width = "400" height = "400">

I get the Uncaught TypeError: Cannot set property 'src' of null error on the document.getElementById("slide").src = images[i]; line. I do not know why, because my array has each photo already in it. They are all within the same folder, so I don't think it's an issue of searching for the photo. Thanks ahead of time.

  • 1
    See the linked question's answers. The element doesn't exist as of when you use `getElementById` to try to find it. Put your `script` at the **end** of the document, just prior to the closing `

    ` tag. More: https://developer.yahoo.com/performance/rules.html#js_bottom

    – T.J. Crowder Nov 27 '18 at 15:59
  • actually, just change `window.onLoad = changeImg()` to `window.addEventListener('load', changeImg)`. The first one calls the function add once, the second one will be attached as event handler for when the document loaded – Icepickle Nov 27 '18 at 15:59
  • 2
    The **reason** it doesn't exist is a bit subtle: `window.onLoad = changeImg();` should be `window.onLoad = changeImg;` (except really, I wouldn't use `onLoad` at all, I'd just move the script as mentioned above). See the [second linked question](https://stackoverflow.com/questions/27643714/settimeout-calls-function-immediately-instead-of-after-delay) for why (that's for `setTimeout`, but it's the same when assigning to `onload` or similar). – T.J. Crowder Nov 27 '18 at 15:59
  • @Pointy - Yeah, I caught that a moment later. It's a combination, I added both dupetargets. – T.J. Crowder Nov 27 '18 at 16:00
  • 1
    Thank you @T.J.Crowder, your suggestion helped me. – Jignesh Jun 06 '20 at 17:44

0 Answers0