Monday, 18 July 2011

Dynamic text resizing using jQuery

<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
<title>Untitled</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"> </script>
<style type="text/css">
  #increase
  {
      
  }
    
    
    #increase:hover
   {
       background-color: aquamarine;
       cursor: pointer;
     }
    #decrease:hover
   {
       background-color: aquamarine;
       cursor: pointer;
   }
</style>

<script type="text/javascript">
 $(function(){
       var type=$('p').css("fontSize").slice(-2);
       var newSize; 
       $('input[type=button]').click(function(){
           var size=$('p').css("fontSize").slice(0,-2);
           if($(this).attr('id')=='increase')
                newSize= (size*1.5)+type;
           else
                newSize= (size/1.5)+type;
           $('p').css({'fontSize': newSize});
       });
      });
</script>

</head>
<body>
    <p>Text to be resized</p>
    <input type="button" id="increase" value="Increase Font-Size"/>
    <input type="button" id="decrease" value="Decrease Font-Size"/>
  
  
</body>
</html>
Explanation
-----------
This was something I was very proud of when I was still a newbie. I got it working, made some
changes, making it more efficient. Till that time I had never thought of efficiency. But, this
changed everything.

The use of slice.
Suppose the font-size returned is 16px, we need to multiply it with a number. We cannot do this
untill we isolate the value, 16 and the unit, px. slice(-2) gives us the last 2 chars, i.e, the
unit. In order to get the size, we use slice(0,-2) i.e, slice from the beginning to untill the
last 2 elements.

We then store the type and size into variable values.
Ok, so this is what I did at first with the jQuery part. Remember that this is the inefficient way.
//when clicked on the increase button,
$('#increase').click(function(){  
   var size=$('p').css("fontSize").slice(0,-2);
   newSize= (size*1.5)+type; //increase the font-size
   $('p').css({'fontSize': newSize});  //Change the font-size

//Similarly,when clicked on the decrease button,
$('#decrease').click(function(){
   var size=$('p').css("fontSize").slice(0,-2);
   newSize= (size/1.5)+type; //decrease the font-size
    $('p').css({'fontSize': newSize});  //Change the font-size

});
But we can make this code even better, more efficient. Instead of doing a check if the radio button
clicked is with an of increase or decrease individually, we can check if the button was clicked on
the first place, then do the following
$('input[type=button]').click(function(){
           var size=$('p').css("fontSize").slice(0,-2);
           if($(this).attr('id')=='increase')
                newSize= (size*1.5)+type;
           else
                newSize= (size/1.5)+type;
           $('p').css({'fontSize': newSize});
As you can see, the code is less and also more efficient.
  

No comments:

Post a Comment