lega
lega

Reputation: 13

Increasing font-size over time

$( "h1" ).hover(
    function(){
        for(var i=0;i<255;i++){

            setTimeout(function(){$("#fat").css("font-size", (i + 12) + "pt")},200);
        }
    }, function(){$("#fat").delay(200).css("font-size","12pt")}
    );

I want to increase the font-size of an Element over time, as long as the mouse is hovered over the text. Though what happens is, that the delay is counted down and then the biggest size is assumed for the Element instantly ( so no pretty growth effect).

I read in another thread (Here) something which is probably related but don't really understand how.

Upvotes: 0

Views: 1993

Answers (4)

Patrick Evans
Patrick Evans

Reputation: 42736

Dont bother with a for loop, do the logic in the anonymous function and use setInterval and clear the interval on hover out or when you have reached the limit

(function(){
   var timer = null;
   $("h1").hover(function(){
      timer = setInterval(function(){
         var ele = $("fat");
         var size = parseInt(ele.css("font-size"));
         if(size>=255){ 
            clearInterval(timer); 
            return;
         }
         ele.css("font-size",(size+1)+"pt"):
      },200);
   },function(){
      clearInterval(timer);
      $("#fat").delay(200).css("font-size","12pt");
   });
})();

Plus to correct the for loop you would have to use a closure and modify the timeout amount through each iteration, otherwise each increase would happen after 200 ms, and not increase once for every 200 ms.

Upvotes: 1

Maen
Maen

Reputation: 10698

Using jQuery

As an alternative to other answers provided, you could use jQuery animate() coupled with hover():

$('#zoomIt').hover(function(){
    $(this).animate({"font-size":"4em"}, 1000); //On mouse on
}, function(){
    $(this).animate({"font-size":"2em"}, 1000); //On mouse out
});

Demo

Using CSS

I prefer the approach of CSS transitions though :

h1 {
    transition: font-size 3s ease-in-out;
    font-size: 2em;
}
h1:hover {
    font-size: 4em;
}

Upvotes: 0

codefreaK
codefreaK

Reputation: 3662

Html

<h1 id="Ex">Some Content</h1>   

Jquery

  $('#Ex').hover(function(){
  //  alert("here");
 for(var i=0;i<10;i++ )
 { 
   setTimeout(function() {
      $("#Ex").delay(2000).css({ zoom: i});
    }, 100);
 }  

});

$("#Ex").mouseout(function() {
$("#Ex").css({ zoom: 0});
});

Demo

Upvotes: 0

Daniel Beck
Daniel Beck

Reputation: 21485

You can do this without any javascript, provided you're willing to set an upper bound on the size you'll allow the item to grow to:

h1 {
    transition: all 10s;
    font-size: 10pt;
}

h1:hover {
    font-size: 100pt;
}

Adjust timing and min/max size to taste.

(But note that animating font-size doesn't look wonderful, it gives you a 'stepped' appearance rather than a smooth zoom. you may be better off using transform: scale() or zoom().)

Upvotes: 0

Related Questions