Reloading an Image with JavaScript

To reload only an image instead of the whole page, assign a fresh URL to the image element's src. A changing query value prevents the browser from reusing the exact cached URL.

const image = document.getElementById('capt');
image.src = `images/help.jpg?cb=${Date.now()}`;
Table of Contents

Reload only the image Top ↑

Help icon used for the image reload demo
The page itself is not reloaded.

Why add a changing query value? Top ↑

If the same URL is assigned again, the browser may reuse its cached response. Adding a unique query parameter such as the current timestamp gives the request a different URL while leaving the underlying image resource unchanged.

image.src = `images/help.jpg?cb=${Date.now()}`;

The original tutorial used Math.random() for the same cache-busting purpose. A timestamp is convenient because it is easy to see that each URL is different.

CAPTCHA use case Top ↑

A common use is a CAPTCHA or other server-generated image. If a visitor cannot read the current CAPTCHA, the Reload button can request a new image without reloading the full form. Plus2net's related server-side example is the CAPTCHA generation tutorial.

<img src="captcha-demo.php" id="capt" alt="CAPTCHA image">
<button type="button" id="reload-image">Reload image</button>

Note: the original JavaScript tutorial referenced a local captcha-demo.php, but that file is not present in the supplied JavaScript source folder. The working demo above therefore uses an existing local image while preserving the same reload technique.

Complete working source Top ↑

The complete source remains available for users to copy.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Reload image without reloading the page</title>
</head>
<body>
  <img src="images/help.jpg" id="capt" alt="Help icon">
  <button type="button" id="reload-image">Reload image</button>
  <p id="status" aria-live="polite"></p>
  <script>
    const image = document.getElementById('capt');
    const button = document.getElementById('reload-image');
    const status = document.getElementById('status');

    button.addEventListener('click', () => {
      image.src = `images/help.jpg?cb=${Date.now()}`;
      status.textContent = 'Image reloaded without reloading the page.';
    });
  </script>
</body>
</html>

Image Object




Subscribe to our YouTube Channel here



plus2net.com







name

24-11-2014

this is great method, thanks for your post,
but i am using like this.

img.src="captcha-demo.php?rand_number=" + (new Date()).getTime());

Kade

25-11-2016

Works great and uses minimal code. Thank you!!



We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer