Reload an image with JavaScript/jQuery
This post will discuss how to refresh an image without reloading the page in JavaScript and jQuery.
1. Using jQuery
To force the browser to fetch the latest version of an image instead of using the cached version, you can simply append a random string at the end of the image URL. This will cause the browser to treat the URL as a different URL and avoid retrieving the cached version.
The following example demonstrates this by appending the current timestamp to the image URL.
JS
|
1 2 3 4 5 6 |
$(document).ready(function() { $("button").click(function() { var url = $("#container").attr("src"); $("#container").attr("src", url + `?v=${new Date().getTime()}`); }); }); |
HTML
|
1 2 |
<img id="container" src='https://avatars0.githubusercontent.com/u/70142'/> <button>Refesh</button> |
Alternatively, you can use a random number instead of the timestamp to force a refresh.
JS
|
1 2 3 4 5 6 |
$(document).ready(function() { $("button").click(function() { var url = $("#container").attr("src"); $("#container").attr("src", url + `?v=${Math.random()}`); }); }); |
HTML
|
1 2 |
<img id="container" src='https://avatars0.githubusercontent.com/u/70142'/> <button>Refesh</button> |
Another plausible way is to first remove the src attribute from <img> element using the .removeAttr() method, and then set it again with .attr() method.
JS
|
1 2 3 4 5 6 |
$(document).ready(function() { $("button").click(function() { var url = $("#container").attr("src"); $("#container").removeAttr("src").attr("src", url); }) }); |
HTML
|
1 2 |
<img id="container" src='https://avatars0.githubusercontent.com/u/70142'/> <button>Refesh</button> |
2. Using JavaScript
In pure JavaScript, you can append a random number or current timestamp at the end of the image URL like:
JS
|
1 2 3 |
document.querySelector("button").onclick = function() { document.getElementById("container").src += `?v=${new Date().getTime()}`; } |
HTML
|
1 2 |
<img id="container" src='https://avatars0.githubusercontent.com/u/70142'/> <button>Refesh</button> |
That’s all about reloading an image in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)