Text Zooming
There are many different ways to create text zooming effects. This article covers how to create an easy JavaScript text zooming component that takes element ids as parameters, and increases or decreases the font size and line height based on the method that is called.
The name of the object that will contain all the functionality for zooming is TextZoom. We start by instantiating a new object and setting the name. With this new object, we can begin to add methods to create the functionality we desire. The first method is called TextZoom.In, which will enlarge the text and create a zoom in effect. This method takes a number of element ids as a parameter and begins iterating through them by using JavaScript’s intrinsic arguments property. While iterating, we gather the current font size of the text and determine whether it is below 24, which is what I have set for the highest pixel size possible for the zoom-in functionality. You can set this number to any size that you like or simply remove the constraints completely. If the condition is met, we add one pixel to the current size and proceed to follow the same steps with the line height. The only difference with the line height is that we do not have a size requirement; this is because the font size requirement will prevent us from getting to this point in the code, leaving it unnecessary to add the additional condition.
The other method that the TextZoom object needs to contain is one that zooms out or decreases the size of the text; we will name this method TextZoom.Out. The easiest way to create this method is to literally duplicate the TextZoom.In method and rename it TextZoom.Out. Once we have our duplicate renamed we change the condition to determine whether the current size of the text is larger than 10. If it is, we’ll proceed with the code as we previously did, but will subtract one pixel from the current size rather than adding one.
Creating the TextZoom Component (TextZoom.js)
var TextZoom = new Object(); TextZoom.In = function() { for(var i=0; i<arguments.length; i++) { var id = arguments[i]; var currentSize = parseInt(document.getElementById(id).style.fontSize); if(currentSize < 24) { document.getElementById(id).style.fontSize = (currentSize+1)+’px’; var currentLineHeight = parseInt(document.getElementById(id).style.lineHeight); document.getElementById(id).style.lineHeight = (currentLineHeight+1)+’px’; } } } TextZoom.Out = function() { for(var i=0; i<arguments.length; i++) { var id = arguments[i]; var currentSize = parseInt(document.getElementById(id).style.fontSize); if(currentSize > 10) { document.getElementById(id).style.fontSize = (currentSize-1)+’px’; var currentLineHeight = parseInt(document.getElementById(id).style.lineHeight); document.getElementById(id).style.lineHeight = (currentLineHeight-1)+’px’; } } }
Now that it has been created, let’s take a look at how to use it.