jophab jophab - 5 months ago 18
HTML Question

Changing image source using JS not working

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>

Answer

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 "on load" event to ensure your script is executed after the DOM is loaded (similar to jQuery's $(function() { }); but using plain JavaScript).

See here: https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onload