Languages
[Edit]
EN

JavaScript - reload image with same URL on click event

0 points
Created by:
Jacob
532

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>

 

See also

  1. JavaScript - reload image with the same URL 

Alternative titles

  1. JavaScript - reload image with same URL onclick()
  2. JavaScript - refresh image with same URL on click event
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join