& ldquo; Zooming & rdquo; elements on one page while keeping the center of magnification at the center of the window

advertisements

I'm trying to work out how to enlarge all elements on a page, but keep the centre of enlargement in the centre of the window.

On this page, once the image reaches the top or the left side of the window the centre of enlargement changes. It also changes when you move the image. (exactly what you would expect)

I'm thinking I'd need to take a completely different approach to achieve what I want. But I'm not sure what that approach is..

Any ideas?


Well, here's my take.

Only thing is that I ditched the containers you were using. Is that cheating? Seems like they were only there to get the image centered. No need.

This works as expected with no side effects.

Here's a working demo you can test:

http://jsfiddle.net/YFPRB/1/

(You need to click on the pane with the baboon first.)

HTML

<body>

<img src="http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png" />

</body>

CSS

html, body {
    width: 100%;
    height: 100%;
    overflow: hidden;
}​

jQuery

EDIT: Thanks to @stagas for the reminder to clean up redundancies.

 var $img = $('img');  // Cache the image. Better for performance.

  $img.draggable();

  $img.css({left: ($('body').width() / 2) - ($img.width() / 2)})
      .css({top: ($('body').height() / 2) - ($img.height() / 2)})

  $(document).keydown(function(event) {

      if (event.keyCode == 38) {
          var adjustment = 1.25;
      } else if (event.keyCode == 40)  {
          var adjustment = 0.8;
      } else {
          return;
      }

      var offset = $img.offset();  

      var width = $img.width();
      var height = $img.height();

      var newWidth = width * adjustment;
      var newHeight = height * adjustment;

      var diffWidth = newWidth - width;
      var diffHeight = newHeight - height;

      var hcenter = $('body').width() / 2;
      var vcenter = $('body').height() / 2;

      var leftPercent = (hcenter - offset.left) / width;
      var topPercent = (vcenter - offset.top) / height;

      $img.offset({top: offset.top - (diffHeight * topPercent), left: offset.left - (diffWidth * leftPercent)});

      $img.width(newWidth).height(newHeight);

    });​