Wednesday, 23 March 2011

Resize chosen fonts dynamically

Again, I can't take much credit for this. The real credit goes to the author of this blog entry http://www.pukkared.com/2010/10/resizing-text-with-jquery-and-window-resize/. I have just made a few changes and calls for my own purposes. Namely, passing which fonts I would like to resize, what the original size should be and what size the page should be before resizing begins. Enjoy!

See demo.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dynamic font resize</title>
<style>
body
{
font-family:Sans-serif;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
 google.load("jquery", "1");
 google.load("jqueryui", "1");
</script>
<script>
$.fn.resizeFonts = function(fontName, originalFontSize)
{
var originalWinWidth = $(window).width();
var ratioOfChange = 50;
$(fontName).css('font-size', originalFontSize);
$(window).resize(function()
{
var winWidth = $(window).width();
var widthDiff = winWidth - originalWinWidth;
if(widthDiff > 0)
{
var pixelsToIncrease = Math.round(widthDiff / ratioOfChange);
var newFontSize = originalFontSize + pixelsToIncrease;
$(fontName).css('font-size', newFontSize);
}
else
{
var pixelsToDecrease = Math.round(Math.abs(widthDiff) / ratioOfChange);
var newFontSize = originalFontSize - pixelsToDecrease;
$(fontName).css('font-size', newFontSize);
}
})
}
$(document).ready(function()
{
$(window).resize(function() {
if($(this).width() < 800)
{
$(this).resizeFonts('h1',20);
$(this).resizeFonts('p',10);
}
});
});
</script>
</head>
<body>
<h1>Big Mick's Recipe Book</h1>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
</body>
</html>

No comments:

Post a Comment