Reputation: 21
I have a page where a random image is loaded using a javascript function.
The below is in the head tag.
function pickimg(){
var imagenumber = 101 ;
var randomnumber = Math.random() ;
var rand1 = Math.round( (imagenumber-1) * randomnumber) + 1;
images = new Array
images[1] = "images/1.jpg"
images[2] = "images/2.gif"
images[3] = "images/3.jpg"
images[4] = "images/4.jpg"
images[5] = "images/5.gif"
images[6] = "images/6.jpg"
images[7] = "images/7.jpg"
images[8] = "images/8.jpg"
images[9] = "images/9.jpg"
var image = images[rand1]
document.randimg.src = image
}
</script>
And then this in the body:
<body onLoad="pickimg()">
<a href="" onClick="pickimg();return false;"><IMG SRC="images/ajax-loader.gif" name="randimg" border=0></a>
A random image is selected. When you click the image, a new one is loaded and THEN displayed. This can take a second or two. I want a ajax-loader to appear as the next image is loading, after the user has clicked. I'm new to this and I've tried various things but nothing gives me the results I desire. Please help, thank you.
Upvotes: 2
Views: 308
Reputation: 1824
An answer, though the Ajax loader is nowhere to be found in your example code, is the following:
getImage: function(fn){
var url = "/apps/blah/imgpath/",
$imgContentContainer = $("myselector");
$imgContentContainer.html(loadingImgTag);
$.ajax({
async: false,
url: url + fn,
success: function(d){ $imgContentContainer.html(theAjaxLoadedImg); }
});
}
Upvotes: 0
Reputation: 1824
First, please replace that code with the following (before end script tag), so that it is proper:
function pickimg(){
var imagenumber = 101, ext,
images = new Array(10), i=0,
randomnumber = Math.random(),
rand1 = 1 + Math.round((imagenumber-1) * randomnumber);
while (++i<10) {
ext = (i===2||i===5)? ".gif" : ".jpg";
images[i] = "images/"+ i + ext;
}
document.randimg.src = images[rand1];
}
Upvotes: 1
Reputation: 324630
Preload the loading image. Then instead of changing the source directly to the new image, change it to the loader, then change it to the new image. This will cause the loader to display immediately (since it's preloaded), and then the new image will appear when it is ready.
Upvotes: 0