Open a Window with Full Size Unscaled Image

Avatar of Chris Coyier
Chris Coyier on (Updated on )

For the gallery section of this site, I wanted people to have the ability to see the screenshot at its original size. Due to the fluid nature of this site, it’s fairly common for the screenshot to be scaled down to fit into its column. So I put together this little solution.

My plan is to open a window the exact size needed to fit the image. Quick, easy, and perfectly good UX in my opinion. All you have to do is this:;

Actually it’s a bit more complex than that. We need to pass in a bunch of parameters to get the window we want. Namely, the kind with as little chrome as possible. A top bar with a close button and that’s about it., null, 'height=y, width=x, toolbar=0, location=0, status=0, scrollbars=0, resizeable=0');


The tricky part is figuring out just exactly what height and width values to pass. You can’t just ask the image what size it is. Well you can, but it will lie. It will tell you its current size, not its natural size.

var img = document.getElementById('screenshot');

img.width;  // current size, not natural size
img.height; // current size, not natural size

To get the natural size, we’ll create a new image in the magical ether of JavaScript, set its source to the source of the on-screen image, and then test its width and height. It will report correctly as it’s untainted by CSS on the page.

var img = document.getElementById('screenshot');
var magicEtherImage = new Image();
magicEtherImage.src = img.src;

var padding = 20; // little buffer to prevent forced scrollbars
// Values to use when opening window
var winWidth = magicEtherImage.width + padding;
var winHeight = magicEtherImage.height + padding;

I use jQuery on my site, so ultimately my code is like this:

$(".view-full-size").click(function() {

  var mainScreenshot = $("#main-screenshot");
  var theImage = new Image();
  theImage.src = mainScreenshot.attr("src");
  var winWidth = theImage.width + 20;
  var winHeight = theImage.height + 20;,  null, 'height=' + winHeight + ', width=' + winWidth + ', toolbar=0, location=0, status=0, scrollbars=0, resizable=0'); 
  return false;

You can see it in action on single gallery pages like this.

Obviously it doesn’t do much on mobile, so I just remove the button with a media query.