Sunday, June 27, 2004

JavaScript: Open Image Links in Popup

The following script makes all links to images open in a popup window. No inline JavaScript required. Modern browser required (i.e. IE5+, NS 6+, Mozilla Firefox). Save into scripts directory and include on page by adding into page <head> tags:

example.html

<html>
<head>
<title>Popup Image Example</title>
<script type="text/javascript" src="scripts/imagepop.js"></script>
</head>
<body>
<p><a href="images/foo.gif" title="Foo Title" width="120" height="300">Foo</a>
| <a href="images/bar.jpg" width="140" height="280">Bar</a>
| <a href="page.html">Baz</a></p>
</body>
</html>

scripts/imagepop.js

function imagepop(url,title) {
	// new window title
	var contents = '<html><head><title>' + ((title)?title:'Image Popup') + '<\/title>';
	// resize window once image has loaded
	contents += '<script type="text\/javascript">window.onload = resize;';
	contents += 'function resize() {';
	contents += 'w=document.images[0].width+25;';
	contents += 'h=document.images[0].height+25;';
	contents += 'window.resizeTo(w,h);';
	// centre the popup window
	contents += 'window.moveTo((screen.width-w)/2,(screen.height-h)/2)}';
	contents += '<\/script>';
	// remove padding and margin using css
	contents += '<style type="text\/css">body{margin:0;padding:0;text-align:center}img{display:block;margin:auto}<\/style>';
	// add image to page
	contents += '<\/head><body><img src="' + url + '">';
	contents += '<\/body><\/html>';
	// open popup window
	imgpop = window.open('about:blank','imgpop','location=no,menubar=no,scrollbars=no,status=no,toolbar=no');
	imgpop.document.open();
	imgpop.document.write(contents);
	imgpop.document.close();
	return false;
}
function checklinks() {
	if(document.getElementsByTagName) {
		// list of image types that are recognised as images
		types = new Array('.jpg','jpeg','.gif','.png','.bmp');
		// get anchor links
		a = document.getElementsByTagName('a');
		// loop through list of anchors
		for (var i=0;i<a.length;i++) {
			// loop through image types
			for (var j=0;j<types.length;j++) {
				/* make sure it links to an image by checking where the extension appears in the string
				   Example 1 (image): http://localhost/image.jpg
				   length of href string is 26, index of .jpg is 22
				   so 26 - 22 = 4 (same length as '.jpg') so linking to an image
				   Example 2 (not image): http://localhost/image.jpg/folder/
				   length of href string is 34, index of .jpg is 22
				   so 34 - 22 = 12 (not the same length as '.jpg') so leave alone
				*/
				if ((a[i].href.length - a[i].href.indexOf(types[j])) == types[j].length){
					// attach onclick event to call the function to open a popup window
					a[i].onclick = function () {
						// pass on href link and title
						return imagepop(this.href,this.title);
					}
				}
			}
		}
	}
}
window.onload = checklinks;

No comments: