EN
JavaScript - reload image with same URL on click event
0
points
In this article, we would like to show you how to reload an image with the same URL on click event using JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
<img src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png"
onclick="changeImage(this)" />
<script>
function changeImage(image) {
image.src = 'https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png?' + Date.now();
}
</script>
Practical example
In this example, we use a unique cache-busting query parameter to reload the image with the same URL on the click event.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<img src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png"
onclick="changeImage(this)" />
<script>
function changeImage(image) {
image.src = 'https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png?' + Date.now();
// display current src
console.log(image.src);
}
</script>
</body>
</html>