O'Reilly

Save Text Size Preference Using MooTools 1.2

By on  

This post was authored by Eric Wendelin. To learn more about Eric, click here.

Last time posting here I taught you how to change text-size with JavaScript. The problem with using the solution I presented as Ian Lloyd pointed out:

Increase the font size, follow a link to another web page on same site and … back to small text

Obviously, the problem here is that we don't remember the user's preferences. It turns out to be very easy using simple JavaScript and PHP. You can view the demo now if you like. For this example I'm going to use the new MooTools 1.2 beta to handle the "cookie jar" so I don't get my hand stuck in it :) OK, let's revise the JavaScript that does the text-sizing:

New and Improved resizeText():

function resizeText(multiplier) 
{   
	var fontsz = "1.0em"; //Default to 1em   
	if (Cookie.get('site_font_size')) 
	{     
		// Use MooTools to get the cookie (if it exists)     
		fontsz = Cookie.get('site_font_size');   
	}   
	fontsz = parseFloat(fontsz) + (multiplier * 0.2) + "em";   // Change body text size   
	document.body.style.fontSize = fontsz;      //Set a new cookie with MooTools   
	
	var myCookie = Cookie.set('site_font_size', fontsz, {     
		domain: 'mydomain.com',
		duration: 365 //Save for 365 days   
	}); 
} 

As you can see this function has grown up into a very useful utility that uses cookies to store and retrieve the value of the current font-size so that the user doesn't have to resize the text after every page load. We could just call resizeText(0) onload but that would cause a flicker on the user's screen and we do not tolerate that when we can do something about it. Using PHP prevents this from happening.

The PHP snippet:

<? echo 'body { font-size:',$_COOKIE['site_font_size'],'; }'; } ?>

Put this snippet immediately after your <link> and <style> tags to prevent any errors.

Now once you have it all ready to test out, I recommend using Firecookie (an extension to Firebug) to verify that it is working exactly as expected. I have a blog post that tells you about all of Firecookie's cool features.

About Eric Wendelin

Eric Wendelin is a software engineer for Sun Microsystems. When he’s not doing super-secret programming for Sun, he plays indoor soccer, playing Wii with his friends, and cheering on the Colorado Avalanche. He also writes a blog on JavaScript, CSS, Java, and Productivity at eriwen.com

O'Reilly Velocity Conference
Save 20% with discount code AFF20

Recent Features

  • Chris Coyier&#8217;s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

  • Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

Incredible Demos

  • Scroll IFRAMEs on iOS

    For the longest time, developers were frustrated by elements with overflow not being scrollable within the page of iOS Safari.  For my blog it was particularly frustrating because I display my demos in sandboxed IFRAMEs on top of the article itself, so as to not affect my site's...

  • CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

Discussion

  1. Perfect with Mootools !
    Thank you very much:)

  2. No problem! MooTools makes it too easy!

  3. Nice script – but IMO, this function should be left to the browser.

  4. @Binny:

    I totally agree, but this functionality is not yet handled properly by all browsers. Furthermore, certain websites have smaller font sizes as part of their design and this code here allows users to customize it for your site.

    It is not the best solution by any means but I think it is a good one for now.

  5. I make a reset body normal (French translation) :

          function resizeText(multiplier) {
            var fontsz = "0.69em"; // Taille de base qui équivaut à 10px
            // Si l'on ne reset pas le css
            if(multiplier != 2) {
            if (Cookie.get('site_font_size')) {
              // Si le cookie existe déjà, on prends sa valeur
              fontsz = Cookie.get('site_font_size');
            }
            fontsz = parseFloat(fontsz) + (multiplier * 0.2) + "em";
            }
            else {
            var fontsz = "0.69em"; // Taille normal qui équivaut à 10px	
            }
            // Changement de la taille du body
            document.body.style.fontSize = fontsz;
            
            // Mise à jour du cookie 
            var myCookie = Cookie.set('site_font_size', fontsz, {
              domain: 'dbdreams.net',
              duration: 365 // 1 an
            });
          }
    
  6. Cosmin

    Firefox 3 > it doesn’t work, meaning I cannot change the text size…have you done something with the links meanwhile?

  7. @Cosmin:
    Oops! I upgraded Mootools from 1.2 beta to 1.2 final and they changed the API!

    Page fixed, and thanks for letting me know!

  8. Geek34

    cookie.get don’t work

  9. @Geek34:
    Yes, the Mootools Cookie class has changed since this was written. The correct functions are Cookie.read() and Cookie.write() respectively :)

  10. Instead of using document.body.style.fontSize = fontsz; you can use morph and change the default unit to em so its a smooth transition instead of the jump in size:

    //set up morph
    var morphTextSize = new Fx.Morph(document.body,{duration:300,transition:Fx.Transitions.linear,'unit':'em'});
    
    //set font size
    morphTextSize.start({
    'font-size': parseFloat(fontsz) + (multiplier * 0.2)
    });
  11. Andy

    There seems to be an error with the way your blog parsed the domain on line 13. For a JS newb like me it was a little confusing for a moment :P

  12. @Andy: Line 13 is fine. What error?

  13. I tried to implement it with jquery and radSlider ASP.NET control. But i reach some problems. After I read comments, and figure out, that best solutions is make “fake” button for text size changing, which shows bubble with something like “Wanna change text size – try CTRL + mouse wheel and if it doesn’t work get better browser”… That’s best solution IMO :)

  14. Richard Clark

    Hi,

    I would like to target by ID a div (eg the ‘content’ div in your example) and change just the text size of this when the button is clicked, and not all of the text.

    How would I amend the following line to do this?

    // Change body text size
    document.body.style.fontSize = fontsz;

    I’ve tried – document.body.getElementById(“content”) = fontsz; but that didn’t seem to work.

    Any help would be greatly appreciated

    Thanks,

    Richard

    • Richard:

      You’ll want something like

      document.getElementById('content').style.fontSize = fontsz;

      Let me know if that doesn’t work for you. Cheers, Eric

  15. Great Post! I was wondering if there is a way to automatically detect the domain to make this script more portable?

    Thanks!

    Best,

    Matt

    • Thanks, Matt.

      You can use “window.location.host” to get the current domain.

      Cheers,
      Eric

  16. Andreas

    I swear noone has tried the PHP-snippet, as its obviously sooo wrong, uah.
    Try this one

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Open Files from Command Line on OS X

    I'm as much of a fan of application UIs as anyone else but I'm finding myself working more and more from the command line lately.  Much of that is becoming obsessed with media manipulation but I'm forcing myself to use less UIs so that I...

  • Get Stock Quotes From Command Line

    When I conned my way into my first professional programming gig, I didn't really think much about money -- just that I was getting my foot in the door.  But as my career has gone on, I've been more aware of money, investing, and retirement.  I've recently...

  • Geolocation API

    One interesting aspect of web development is geolocation; where is your user viewing your website from? You can base your language locale on that data or show certain products in your store based on the user's location. Let's examine how you can...

  • Create an Image Preview from a Video

    Visuals are everything when it comes to media.  When I'm trying to decide whether to watch a video on Netflix, it would be awesome to see a trailer of some kind, but alas that isn't available.  When I'm looking to download a video on my computer,...

  • New:  Webdesigner News!

    A new and exciting website has recently been launched for web designers and developers. You likely spend hours every morning browsing through hundreds of posts on your RSS feeds, hoping to stumble across relevant stories. Webdesigner News was built to provide web designers and developers with...