Preloading Images with the DOM: A Functional Image-Preloading Application - Displaying enlarged images: coding the “displayImage()” function
(Page 4 of 5 )
Fortunately, displaying zoomed-in pictures is a fairly easy thing to do. But in fact, I’m getting ahead of myself. So, let me first define the “displayImage()” function and then I’ll discuss its rationale. Below is its definition:
function displayImage(elemid){
var cdiv=document.getElementById('container');
if(!cdiv){createImageContainer()};
var newpic=pics[elemid];
var oldpic=document.getElementById('largepic');
if(!oldpic){return};
oldpic.setAttribute('src',newpic.src);
}
In order to display a zoomed-in images, the function above will first check for the existence of the “container” <div> element that you just saw in the previous section. Since I want the function to show only one <div> for displaying images, the “createImageContainer()” function will be called up either the first time the user clicks on a thumbnail or when the containing <div> has been removed from the web document. The following line demonstrates this condition:
if(!cdiv){createImageContainer()};
Now, the process for swapping zoomed-in images is performed by utilizing the lines below:
var newpic=pics[elemid];
var oldpic=document.getElementById('largepic');
if(!oldpic){return};
oldpic.setAttribute('src',newpic.src);
There are a couple of things that require our attention here. Notice the new image for display is stored in the “newpic” variable. Then, the old picture is replaced within the container with the new one by manipulating its “src” attribute, as follows:
oldpic.setAttribute('src',newpic.src);
Since all the images were previously preloaded into memory, the swapping process between pictures will be executed with practically no delays. As I explained before, this function looks a lot like a multiple image swapper.
By this point, all the functions of the script have been defined and properly discussed. Keeping in mind that now the script is capable of preloading all the larger images, and displaying each of them with a subtle lag, it’s time to group all the functions into a single snippet and run it after the page has been loaded. Considering this, let’s jump straight into the next section and see how the complete application looks.
Next: Gluing the pieces: turning the application into a functional AJAX-based preloader >>
More JavaScript Articles
More By Alejandro Gervasio