javascript closure: a simple example of a javascript function created via closure

javascript closure:

here is a small example of an anonymous javascript function, that is used to create a function.

the advantage is, that variables used to set up the function, are wrapped within the scope of the anonymous function, which:
  • prevents tampering with the function
  • keeps the global namespace clean
 var fontDetectionJsOnly = {};  
 fontDetectionJsOnly.detector = function () {  
           var test_string = 'mmmmmmmmmwwwwwww';  
           var test_font = '"Comic Sans MS"';  
           var notInstalledWidth = 0;  
           var testbed = null;  
           var guid = 0;  
           return {  
             // must be called when the dom is ready  
             setup: function () {  
               if ($('#fontInstalledTest').length) return; //already setup  
               $('head').append('<' + 'style> #fontInstalledTest, #fontTestBed { position: absolute; left: -9999px; top: 0; visibility: hidden; } #fontInstalledTest { font-size: 50px!important; font-family: ' + test_font + ';}</' + 'style>');  
               $('body').append('<div id="fontTestBed"></div>').append('<span id="fontInstalledTest" class="fonttest">' + test_string + '</span>');  
               testbed = $('#fontTestBed');  
               notInstalledWidth = $('#fontInstalledTest').width();  
             },  
             isInstalled: function (font) {  
               guid++;  
               var style = '<' + 'style id="fonttestStyle"> #fonttest' + guid + ' { font-size: 50px!important; font-family: ' + font + ', ' + test_font + '; } <' + '/style>';  
               $('head').find('#fonttestStyle').remove().end().append(style);  
               testbed.empty().append('<span id="fonttest' + guid + '" class="fonttest">' + test_string + '</span>');  
               return (testbed.find('span').width() != notInstalledWidth);  
             }  
           };  
         }();  

note: the anonymous function is called immediately, via the final brackets (), when the page is loaded.

Usage:
for completeness, here is an example of how to use the create function.

the created function fontDetectionJsOnly.detector.isInstalled() is used to detect whether a font is installed.

 fontDetectionJsOnly.detector.setup();  
 var isCourierInstalled = fontDetectionJsOnly.detector.isInstalled(‘Courier’);  

Credit:
credit for this example goes to remysharp.com:

reference: http://remysharp.com/2008/07/08/how-to-detect-if-a-font-is-installed-only-using-javascript/

Comments