0

I am trying to change src of an image based on day. But the src is not updating. What is the problem?

    <head>
<script type="text/javascript">
image = new Array(7);
image[0] = 'img/about-img1.jpg';
image[1] = 'img/about-img2.jpg';
image[2] = 'img/about-img3.jpg';
image[3] = 'img/about-img4.jpg';
image[4] = 'img/about-img1.jpg';
image[5] = 'img/about-img4.jpg';
image[6] = 'img/about-img5.jpg';
var currentdate = new Date();
var imagenumber = currentdate.getDay();
document.getElementById("special").src=image[imagenumber];
</script>
</head>
<body>
<img  id="special" src="">
</body>
jophab
  • 5,356
  • 14
  • 41
  • 60
  • 1
    What is `ImageArray`? Perhaps you meant `Array`. – Turnip Jun 16 '16 at 14:01
  • Are you using MasterPages to build the page? If so, the name of the element may have "MainContent_" attached to the front of the ID preventing you from finding it with getelementbyID... – Rick Runowski Jun 16 '16 at 14:04

2 Answers2

3

You're trying to access the DOM before it is even loaded. Put the script tag below the <img> at the end of the <body> tag.

<body>
<img  id="special" src="">

<script type="text/javascript">
image = new ImageArray(7);
image[0] = 'img/about-img1.jpg';
image[1] = 'img/about-img2.jpg';
image[2] = 'img/about-img3.jpg';
image[3] = 'img/about-img4.jpg';
image[4] = 'img/about-img1.jpg';
image[5] = 'img/about-img4.jpg';
image[6] = 'img/about-img5.jpg';
var currentdate = new Date();
var imagenumber = currentdate.getDay();
document.getElementById("special").src=image[imagenumber];
</script>
</body>

Alternatively, look into using a window.onload event to ensure your script is executed after the DOM is loaded (similar to jQuery's $(function() { }); but using plain JavaScript).
See here

Stacked
  • 6,892
  • 7
  • 57
  • 73
Omar Himada
  • 2,540
  • 1
  • 14
  • 31
0

The solution is to place the javaScript code in the body after the <img> tag. Using it in the head executes it, before the image DOM element exists and so getElementById() doesn't find anything.

<head>
</head>
<body>
  <img  id="special" src="">
  <script type="text/javascript">
    var image = [1, 2, 3, 4, 1, 4, 5],
        currentdate = new Date();
    document.getElementById("special").src = 'img/about-img' + image[currentdate.getDay()] + '.jpg';
  </script>
</body>
JSchirrmacher
  • 3,243
  • 2
  • 19
  • 27