Skip to content

Instantly share code, notes, and snippets.

@omgmog
Last active August 29, 2015 14:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omgmog/451708d32b76b8bfe8e6 to your computer and use it in GitHub Desktop.
Save omgmog/451708d32b76b8bfe8e6 to your computer and use it in GitHub Desktop.
Conditionally change fonts in a page
// Here you specify the fonts that you don't want to change, so as not to conflict with icon fonts, etc.
var excludedFonts = ["FontAwesome", "Icomoon", "Fontelico", "octicons", "Entypo", "Typicons"];
// Here you specify your new font for everything else
var newFont = "ComicSansMS, Arial";
// Wrap the changer as a function
var conditionallyChangeFont = function () {
// Here be dragons. Lots of DOM traversal
var els = document.querySelectorAll('body *');
for (var i=0;i<els.length;i++) {
var elementFonts = window.getComputedStyle(els[i],null).getPropertyValue("font-family").split(',');
var changeFont = true;
for (var _i=0;_i<elementFonts.length;_i++) {
for (var __i=0;__i<excludedFonts.length;__i++) {
if (elementFonts[_i] === excludedFonts[__i]) {
changeFont = false;
}
}
}
if (changeFont) {
els[i].style.fontFamily = newFont;
}
}
};
// Set up the MutationObserver
var target = document.querySelectorAll('body')[0];
var observer = new MutationObserver(function(changes) {
changes.forEach(function(change) {
conditionallyChangeFont();
});
});
observer.observe(target, { attributes: true, childList: true});
// And then call conditionallyChangeFont for good measure
conditionallyChangeFont();
@omgmog
Copy link
Author

omgmog commented Jul 16, 2015

@omgmog
Copy link
Author

omgmog commented Jul 16, 2015

Updated to use MutationObserver so that new DOM nodes get the font applied.

@peterjwest
Copy link

Nice!

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