Last active
August 29, 2015 14:07
-
-
Save fijiwebdesign/71fb0ef50e6548d43cac to your computer and use it in GitHub Desktop.
Detect font-family of element in jquery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.