Skip to content

Instantly share code, notes, and snippets.

@fijiwebdesign
Last active August 29, 2015 14:07
Show Gist options
  • Save fijiwebdesign/71fb0ef50e6548d43cac to your computer and use it in GitHub Desktop.
Save fijiwebdesign/71fb0ef50e6548d43cac to your computer and use it in GitHub Desktop.
Detect font-family of element in jquery
/**
* Detects the font of an element from the font-family css attribute by comparing the font widths on the element
* @link http://stackoverflow.com/questions/15664759/jquery-how-to-get-assigned-font-to-element
*/
(function($) {
$.fn.detectFont = function() {
var fontfamily = $(this).css('font-family');
var fonts = fontfamily.split(',');
if ( fonts.length == 1 )
return fonts[0];
var element = $(this);
var detectedFont = null;
fonts.forEach( function( font ) {
var clone = $('<span>wwwwwwwwwwwwwwwlllllllliiiiii</span>').css({'font-family': fontfamily, 'font-size':'70px', 'display':'inline', 'visibility':'hidden'}).appendTo('body');
var dummy = $('<span>wwwwwwwwwwwwwwwlllllllliiiiii</span>').css({'font-family': font, 'font-size':'70px', 'display':'inline', 'visibility':'hidden'}).appendTo('body');
//console.log(clone, dummy, fonts, font, clone.width(), dummy.width());
if ( clone.width() == dummy.width() )
detectedFont = font;
clone.remove();
dummy.remove();
});
return detectedFont;
}
})(jQuery);
@fijiwebdesign
Copy link
Author

This doesn't work with block elements as width is not defined by font.

@fijiwebdesign
Copy link
Author

Need to create two inline elements. One with the font family of the tested element, and one with font family of each individual font and test widths.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment