Home Ajax XUL JavaScript CSS HTML 5 FAQ-Forum

Ajax Script To Scale Images

What we want is to present a gallery of images or just thumbnails, and when the mouse passes over an image, the image appears in full size. The advantage of using Ajax is in asynchronous mode unique to the XMLHttpRequest object, which we will allow loading images when the page is already loaded, and while the user reads the page, without any delay at loading of the page, or at display of the image...

function preloading(url)
{
	var xhr=createXHR();   
	xhr.onreadystatechange=function()
	{ 
		if(xhr.readyState == 4)
		{
			var content = xhr.responseText;
			var i = new Image();
			i.src = content;
		} 
	}; 

	xhr.open("GET", url , true);
	xhr.send(null); 
} 

The demo

In this demo, we put a gallery of thumbnails on the left, in a div whose ID is "leftview" and at the center of the page a field is ready to display the full image, with the name "bigview."

At each thumbnail is associated a "onmouseother" HTML method, which triggers an event when the mouse passes over the small image. If one prefers to view the image only when the user clicks on the thumbnail, "onclick" may be used instead.
The associated value is "enlarge (this)" that calls the JavaScript "enlarge" function with the parameter "this", which represents the current img tag.
The function enlarge builds an img tag to be placed in the central display space. It assumes that the labels have the prefix "thumb-" and the images in full size the prefix "big-". Simply change the prefix to have the name of the image for each thumbnail.

function enlarge(element)
{
	var name = element.src;
	
	name = localFilename(name);       // remove the path
    name = name.slice(6);           // remove the "thumb-" part
	name = "images/big-" + name;    // restore the path and adds "big-" prefix
		
	// building a string to display the image
	
   var str = " < img='" + name + "'>";
   document.getElementById("bigview").innerHTML = str;
}


License: (c) 2006-2007 Xul.fr & Denis Sureau. You are free to use the code of the demos to motorize your site. Please do not put the demos on another website. You can also print the code and distribute it for educational purpose.