How to reload images using JavaScript

Web programming topics
Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to reload images using JavaScript

Post by Neo » Mon Mar 01, 2010 12:52 am

There are some situations where you want to reload an image without refreshing the page containing it. This is especially handy with CAPTCHA images, where you might want to give the user the option to get a new code in case the first is too hard to read.

It sounds simple enough, but then there is browser caching that you need to work around. Fortunately, this problem is easy to solve just by altering the URL of the source, adding a unique string to the end (such as a timestamp) as a GET parameter. Here is a little JavaScript function that will accomplish this:

Code: Select all

function reloadImg(id) {
   var obj = document.getElementById(id);
   var src = obj.src;
   var pos = src.indexOf('?');
   if (pos >= 0) {
      src = src.substr(0, pos);
   }
   var date = new Date();
   obj.src = src + '?v=' + date.getTime();
   return false;
} 
To use it, all you need to do is pass the id of the image to the function, like this:

Code: Select all

<img src="image.jpg" id="img" />
<a href="#" onClick="return reloadImg('img');">Reload Image</a> 
I haven't tested it, but this should also work for other elements that use the src attribute.
Post Reply

Return to “Web programming”