Preloading Images with the DOM: A Functional Image-Preloading Application - Building image containers: defining the “createImageContainer()” function
(Page 3 of 5 )
As you probably remember, after all the images have been preloaded into memory, it’s necessary to display the zoomed-in picture corresponding to the thumbnail that was clickedn. Considering that each image will require a wrapping element within the Web document, before displaying the pertinent picture, I’ll define a simple function, “createImageContainer()”, which will be responsible for creating a DIV element, in order to house the picture itself, together with the window-closing paragraph. Here is what this function looks like:
function createImageContainer(){
// create image container
var cdiv=document.createElement('div');
cdiv.setAttribute('id','container');
var img=document.createElement('img');
img.setAttribute('width','400');
img.setAttribute('height','277');
img.setAttribute('id','largepic');
// create 'close' paragraph
var p=document.createElement('p');
p.appendChild(document.createTextNode('Close window[-]'));
cdiv.appendChild(p);
cdiv.appendChild(img);
document.getElementsByTagName('body')[0].appendChild(cdiv);
p.onclick=function(){
this.parentNode.parentNode.removeChild(this.parentNode);
}
}
Having defined the above function, let’s break down its code into pieces and see how it works. First, the function begins creating the containing <div> element, along with an <img> element. Then, it assigns some attributes to the elements just created, such as ID for the DIV, as well as “width” and “height” for the image. Surely, you’re wondering what the reason is for including an <img> element. If you’re used to working with old image swappers, the answer is pretty straightforward, since the script will switch between images by manipulating their “src” attribute. See how old techniques are merged with modern technology?
Now, returning to the remaining code, it’s fairly self-explanatory. As you can see, a <p> element is created on top of the containing <div>, in order to provide users with a simple control for removing the image they're seeing from the document. By studying the last lines of the function, the <div> element is removed through the following expression:
p.onclick=function(){
this.parentNode.parentNode.removeChild(this.parentNode);
}
Having illustrated the way that the script builds in the containing element for displaying large images, the next step will be defining a function that shows zoomed-in pictures. Thus, join me in the next section to find out how this process is carried out.
Next: Displaying enlarged images: coding the “displayImage()” function >>
More JavaScript Articles
More By Alejandro Gervasio