Skip to content

Instantly share code, notes, and snippets.

@BananaAcid
Forked from andrewbranch/autoshrink.js
Last active October 20, 2016 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BananaAcid/3908088e0d13bfb25a5e2f233f9aefb1 to your computer and use it in GitHub Desktop.
Save BananaAcid/3908088e0d13bfb25a5e2f233f9aefb1 to your computer and use it in GitHub Desktop.
Responds to window resize events. Max font size taken from initial font size (specify with CSS). [no modifications, just forked to extend the example.]
(function($) {
function getTextWidth($element) {
var tester = $("<div/>").text($element.text())
.css({ "position": "absolute", "float": "left", "white-space": "nowrap", "visibility": "hidden", "font": $element.css("font"), "text-transform": $element.css("text-transform"), "letter-spacing": $element.css("letter-spacing") })
.appendTo($element.parent()),
width = tester.innerWidth();
tester.remove();
return width;
}
function AutoShrinker($element) {
this.$element = $element;
this.$parent = $element.parent();
this.initialFontSize = parseFloat($element.css("fontSize"));
this.currentFontSize = this.initialFontSize;
this.leftMarginRatio = parseFloat($element.css("marginLeft")) / this.initialFontSize;
this.resize = function() {
var maxWidth = this.$parent.width(),
newSize = this.currentFontSize * (maxWidth / getTextWidth(this.$element));
newSize = newSize > this.initialFontSize ? this.initialFontSize : newSize;
this.$element.css({
"fontSize": newSize,
"marginLeft": newSize * this.leftMarginRatio
});
this.currentFontSize = newSize;
};
}
$.fn.autoshrink = function() {
return this.each(function() {
var shrinker, $this = $(this);
$this.data("autoshrinker", shrinker = new AutoShrinker($this));
shrinker.resize();
$(window).on("resize", function() {
shrinker.resize();
});
});
};
})(jQuery);
<script>
$('h1').get(0).style = ''; // reset all styles to reapply autoshrink()
$('h1').autoshrink();
</script>
<div>
<h1>Shrink Me</h1>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment