UltraMega Blog
21Dec/087

Reloading Images Using JavaScript

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:

1
2
3
4
5
6
7
8
9
10
11
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:

<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.

Try it here:

Reload Image

Similar Posts:

 

About Steve

Steve is the owner of UltraMega Tech. He is a freelance Web designer and developer who specializes in PHP and AJAX development.
Comments (7) Trackbacks (0)
  1. Thank you it helped me a lot

  2. Great job man, nice browser cache trouble workaround for same img name but diff content.

    Thanks a lot.

  3. If you have control of the server side, you can disable the caching over on that end. Changing the query string is a pretty clean hack though

    http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9

  4. i have used this code in my site…thanks for the useful code kit….

  5. Great! Big thanks!

  6. perfect, u save my day!


Leave a comment


No trackbacks yet.

Page optimized by WP Minify WordPress Plugin