s4suryapal
s4suryapal

Reputation: 1960

zoom-in(increase) zoom-out(decrease) font using jquery css

I want to implement zoom-in(increase) zoom-out(decrease) font using jquery and css

I tried lots of plugin but its not accurate, Have a look here is my code:

<script type="text/javascript">
var $ = jQuery
var section = '#contents *';
var originalFontSize = $(section).css('font-size');  
function resetFont(){
    $(section).css('font-size', originalFontSize);
}
function increaseFont() {
    $(section).each(function(idx, el){
        var currentFontSize = $(this).css('font-size'),
            currentFontSizeNum = parseFloat(currentFontSize, 10),
            newFontSize = currentFontSizeNum * 1.2;
        $(this).css('font-size', newFontSize);              
    });
}
function decreaseFont(){

    $(section).each(function(idx, el){
        var currentFontSize = $(this).css('font-size');


        var currentFontSizeNum = parseFloat(currentFontSize, 10);
        var newFontSize = currentFontSizeNum*0.8;

        $(this).css('font-size', newFontSize);        
   });
}
</script>

<div id='contents'>
<div>
Any text here
</div>
</div>
<input type='button' value='zoom' onclick='increaseFont()' />
<input type='button' value='zoom out' onclick='decreaseFont()' />

here zoom in once and zoom out once,and see its not back to normal size

Working Fiddle : Fiddle

Upvotes: 2

Views: 4750

Answers (1)

Me.Name
Me.Name

Reputation: 12544

As mentioned, increasing with a percentage, and decreasing the changed value with the same percentage does not give the original value. Best is to keep one factor constant, and either multiply or divide by it (where dividing is the same as multiplying with 1/factor)

Further, the code uses an each for what now is a single element, so I assumed in my example, that you wanted to increase child elements individually. Getting the current font size is centralized, where the originalValue is kept at the same time per element.

(At my current location I can't use jsfiddle, so I used jsbin instead:)

JSBin Demo

var section ;
var factor = 0.8;

function getFontSize(el)
{
    var fs = $(el).css('font-size');    
    if(!el.originalFontSize)el.originalFontSize =fs; //set dynamic property for later reset  
    return  parseFloat(fs);  
}

function setFontSize(fact){
    if(section==null)
       section = $('#contents').find('*')       
       .filter(
         function(){return  $(this).clone()
            .children()
            .remove()
            .end()
            .text().trim().length > 0;
            }); //filter -> exclude all elements without text

    section.each(function(){  
      var newsize = fact ? getFontSize(this) * fact : this.originalFontSize;
      if(newsize) $(this).css('font-size', newsize );      
    }); 
}

function resetFont(){
    setFontSize();
}
function increaseFont() {
    setFontSize(1 / factor);
}
function decreaseFont(){
    setFontSize(factor);
}

Upvotes: 3

Related Questions