Your main problem is that you haven't set up the second image and then, when you do, there needs to be code that somehow toggles between them.
There are many variations on how to do this, but IMHO the simplest and most scaleable is to keep the URLs for the images in an array and then upon the click of the button, update the img
src
to the next array item. When you reach the end of the array, start over at the beginning.
As a side (but important) note, you are using .getElementsByTagName()
with an index, which is not a very good technique for getting a DOM element reference and should be avoided. Instead, you should use modern APIs such as .querySelector()
and .querySelectorAll()
(discussed in the previous link).
Finally, a form field element like a button
should only have a name
attribute when it is nested inside of a form
that will be submitting data somewhere and the value
of that element is desired to be submitted along with the rest of the form
data.
// Store URLs in an array
let urls = ["https://upload.wikimedia.org/wikipedia/commons/thumb/e/e9/Check_mark.svg/28px-Check_mark.svg.png", "https://www.barcoproducts.com/media/catalog/product/cache/1de18e47886e8a56e4b449f2e3cefe99/R/W/RW925_630.jpg"];
let index = 0; // Keep a reference to which URL is being used
// There are different ways to get element references:
var img = document.querySelector("img");
var button = document.getElementById("button");
button.addEventListener("click",showPic);
function showPic(e) {
// Don't work with inline styles. Just work with
// CSS classes and the element's classList
img.classList.remove("hidden");
// Adjust the image source
if(index < urls.length - 1){
index++; // Increase the index
} else {
index = 0; // Reset index
}
// Change the image source
img.src = urls[index];
}
button{
display: block;
position: relative;
left: 7%;
}
.hidden {
display: none;
}
img { width:50px; }
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
<title></title>
</head>
<body>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e9/Check_mark.svg/28px-Check_mark.svg.png" alt="image" class="hidden">
<button type="picture" id="button">Click Me</button>
<script src="index.js" charset="utf-8"></script>
</body>
</html>