October 7, 2001 - Incrementing the Current Zoom Factor | WebReference

October 7, 2001 - Incrementing the Current Zoom Factor

Yehuda Shiran October 7, 2001
Incrementing the Current Zoom Factor
Tips: October 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

One way to zoom in and out of an element is by incrementing or decrementing the current zoom factor. You can decide for yourself the increment by which you want to go. This zooming method avoids prompting the user for any zoom number. You just provide the user with one button to zoom in and one button to zoom out. Play around with the following Zoom In and Zoom Out buttons. See the effect on the text below ("Press any button above and see the effect!"):

Press any button above and see the effect!
The two buttons are defined as follows:

<INPUT TYPE="button" VALUE="Zoom In" onmouseup="zoomInAndOut('in')">
<INPUT TYPE="button" VALUE="Zoom Out" onmouseup="zoomInAndOut('out')">
The event handler zoomInAndOut() handles both cases ("in" and "out"):

function zoomInAndOut(string) {
  if (string == "in") {
    currZoom = container1.style.zoom;
    currZoom = currZoom.substring(0, currZoom.length - 1);
    currZoom = parseInt(currZoom, 10);
    newZoom = currZoom + 1;
	
    if (newZoom > 10000) return;
	
    container1.style.zoom = newZoom + "%";
  }
  else if (string == "out") {
    currZoom = container1.style.zoom;
    currZoom = currZoom.substring(0, currZoom.length - 1);
    currZoom = parseInt(currZoom, 10);
    newZoom = currZoom - 1;
	
	if (newZoom < 1) return;
	
    container1.style.zoom = newZoom + "%";
  }
}
The algorithm is straightforward. We determine the current zoom factor, extract the substring without the % sign, convert to integer, and then either add or subtract a one. We then add the % sign back and set the zoom property to the new zoom factor.