How to update an image on a page

Say you have a picture on a page and there is a button to rotate it using ajax. If the image is rotated, then you need to update the image that's displayed on the screen to show that it's been rotated.

Basically, just append a query string to the src that is random.

Here is a snippet of jQuery demonstrating this.

The first step is to get the src of the image, then check to see if there is a ?. If so, then you need to append an &. If not, then you need to add a ?. Then you can append the randomness. In this case, r=Math.random().

srcOfImage = $("#admin_command_" + command + span_number).siblings("a.image_thumb").children("img.thumb").attr("src");
if (srcOfImage.indexOf('?') == -1) {
    srcOfImage += '?';
} else {
    srcOfImage += '&';
}
srcOfImage += "r=" + Math.random();
$("#admin_command_" + command + span_number).siblings("a.image_thumb").children("img.thumb").attr("src", srcOfImage);

The resulting image will look like,

<img src="http://www.example.com/myimage.jpg?r=2323523523532" />

or this if you change the picture multiple times.

<img src="http://www.example.com/myimage.jpg?r=2323523523532&r=234234234&r=32523523523523" />

Page Comments (Click to edit)






[Click to add or edit comments])

Please prepend comments below including a date

Design by N.Design Studio, adapted by solidGone.org (version 1.0.0)
Have a nice day.