1. Home
  2. Computing & Technology
  3. JavaScript

Popup Windows

9. Captioned Image Popups

clr gif

Picture of Stephen Chapman at the AMRA 50th Anniversary ConventionLet's now go one step further than just creating a popup window containing a larger version of the thumbnail image. Let's create a complete web page to hold both the image and a cation describing the image. We can also set it up so that the window closes automatically when the mouse is clicked anywhere in the popup.

We will begin by looking at the code for the function that displays the popup. The code to do this is a combination of most of what we have learned in the earlier tutorials. It looks like this:

function goImgWin(myImage,myWidth,myHeight,
continued from previous lineorigLeft,origTop,capt) {
var mh = myHeight + 44;
var mw = myWidth + 24;
TheImgWin = window.open('','image','height=' + mh +
continued from previous line ',width=' + mw + ',toolbar=no,directories=no,
continued from previous linestatus=no,' + 'menubar=no,scrollbars=no,resizable=no');
TheImgWin.resizeTo(mw+2,mh+30);
TheImgWin.document.write('<!DOCTYPE html
continued from previous line PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
continued from previous line "http://www.w3.org/TR/xhtml1/DTD/xhtml
continued from previous line1-transitional.dtd"><html xmlns="http:\/\/www.w3.org
continued from previous line\/1999\/xhtml">');
TheImgWin.document.write('<head><title>Popup<\/title
continued from previous line><\/head>');
TheImgWin.document.write('<body style="overflow:hidden"
continued from previous line bgcolor="#ffffff" onclick="self.close()">');
TheImgWin.document.write('<img src="'+myImage+'"
continued from previous line width="'+myWidth+'" height="'+myHeight+'" ');
TheImgWin.document.write('border="0" alt="'+capt+'"\/><p
continued from previous line align="center">'+capt+'<\/p>');
TheImgWin.document.write('<\/p><\/body><\/html>');
TheImgWin.moveTo(origLeft,origTop);
TheImgWin.focus();
}

The code for the thumbnail image also needs to be changed slightly to this:

<a href="graphics/convent.jpg" target="_blank"
onclick="goImgWin('graphics/convent.jpg',240,302,100,50
continued from previous line,'Stephen Chapman'); return false;"
><img src="graphics/convent_t.jpg"
width="57" height="72" border="1"
alt="Picture of Stephen Chapman at the AMRA 50th Anniversary Convention" align="left" /></a>

Well there you are, a popup window that sizes itself appropriately to display an image along with a short caption that will also close itself automatically when the window is clicked on.

Explore JavaScript

More from About.com

  1. Home
  2. Computing & Technology
  3. JavaScript
  4. Windows and Frames
  5. Popup Windows
  6. Captioned Image Popups

©2008 About.com, a part of The New York Times Company.

All rights reserved.