I'm trying to change the src attribute of an image each time a button is clicked, and when the last image appears, then it resets and displays the initial image.
I get the src attribute of the image, and update it to new image, but the image does not change.
var imgSrc = document.querySelector("#myImg").src;
imgSrc = images[i]; /* Is not working */
Could you help me please? Thanks in advance.
<!DOCTYPE html>
<html>
<head></head>
<body>
<img width="60%" id="myImg" src="https://i.imgur.com/TiipKoJ.gif"/>
<br><br>
<button onclick="changeImg ()">Change Image</button>
<script>
var i = 0, images = ["https://i.imgur.com/TiipKoJ.gif", "https://i.imgur.com/QHOn5G9.gif", "https://i.imgur.com/wRbhXbc.gif", "https://i.imgur.com/wbegtAO.gif", "https://i.imgur.com/UIXLgFX.gif"];
function changeImg() {
var imgSrc = document.querySelector("#myImg").src;
if (i < 3) {
i++;
imgSrc = images[i];
} else {
i = 0;
imgSrc = images[i];
}
}
</script>
</body>
</html>
srcproperty also i.e.document.querySelector("#myImg").src = imgSrcvar imgSrc = document.querySelector("#myImg").src;wil copy the value, since it's a string. You have a set the value directly :document.querySelector("#myImg").src = "./whatever.png"