Tuesday, July 12, 2011

How to zoom element text on Mouseover using jQuery

For one of my requirement, I need to zoom in the text of div element on mouseover and zoom out on mouseout. This was fairly simple with jQuery so I thought to share with you. For example, you want to zoom in the text placed in a div with ID "Content". The default style applied to "Content" div element is below.
#content
{
font-size:10pt;
font-family:Arial,sans-serif;
}
On jQuery side, you need to do following things.
  1. Fetch the existing size of the element and store it in any variable.
  2. Double the existing size and store in another variable.
  3. Set the font size to doubled size on mouseover event of element.
  4. Set the font size to original size on mouseover event of element.
That's it. See jQuery code below.
$(document).ready(function() {
  var oldSize = parseFloat($("#content").css('font-size'));
  var newSize = oldSize  * 2;
  $("#content").hover(
    function() {
     $("#content").animate({ fontSize: newSize}, 200);
    },
    function() {
    $("#content").animate({ fontSize: oldSize}, 200);
   }
 );
});
Rather than using mouseover and mouseout method seperately, jQuery provides another method named "hover()" which serves purpose of both the methods. Please read more here about hover().
See live Demo and Code.
Also Read:
Feel free to contact me for any help related to jQuery, I will gladly help you.