I am a self-taught beginner programmer and I'm working on a personal project. I'm having trouble making my code work.
Essentially, I would like to have a button which, when clicked, refreshes the image element on my page. For the image, I use a {placekitten} link.
Here is my HTML:
<body>
<div class="container">
<button id="kitten-reload">Reload kitten</button>
<div class="image-container">
<img
id="kitten-image"
src="http://placekitten.com/300/300"
alt="Cute kittens"
/>
</div>
</div>
</body>
And here is my JS:
const reloadBtn = document.querySelector("#kitten-reload");
const kittenImage = document.querySelector("#kitten-image");
const kittenURL = "http://placekitten.com/300/300";
reloadBtn.addEventListener("click", () => {
kittenImage.removeAttribute("src", "");
kittenImage.setAttribute("src", kittenURL);
});
I thought that removing the src attribute and adding a new one afterwards would work, but the image does not change.
What I tried before this:
- creating a function to add a dummy timestamp string at the end of the link (it only worked on the first click)
- trying .load() on the image element (that also involved some JQuery which I'm not familiar with so maybe I messed it up)
I appreciate any suggestions, thank you :)