Skip to content

Instantly share code, notes, and snippets.

@pencilcheck
Created January 10, 2018 16:58
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 pencilcheck/9357276ffed1c83e57f9b2aa43db9b92 to your computer and use it in GitHub Desktop.
Save pencilcheck/9357276ffed1c83e57f9b2aa43db9b92 to your computer and use it in GitHub Desktop.
module.exports = function extend($) {
$.fn.autoSizr = function(options) {
var el, elements, _i, _len, _results
elements = $(this)
if (elements.length < 0) {
return
}
_results = []
for (_i = 0, _len = elements.length; _i < _len; _i++) {
el = elements[_i]
_results.push(
(function(el) {
function growSize(oldSize) {
return `${oldSize + 1}px`
}
function shrinkSize(oldSize) {
return `${oldSize - 1}px`
}
var resizeText, _results1
resizeText = function(changeSize = shrinkSize) {
var elNewFontSize
elNewFontSize = changeSize(getFontSize(el))
return $(el).css('font-size', elNewFontSize)
}
function getFontSize(el) {
return parseInt($(el).css('font-size').slice(0, -2))
}
function getHeightWithoutPadding(el) {
if (!getComputedStyle) {
console.warn(
'autoSizr: current browser does not support getComputedStyle'
)
}
var computedStyle = getComputedStyle
? getComputedStyle(el)
: { paddingTop: 0, paddingBottom: 0 }
var height =
el.clientHeight -
(parseFloat(computedStyle.paddingTop) +
parseFloat(computedStyle.paddingBottom))
return height
}
$(el).css('line-height', '1em')
// Option 2, shrinking font size to fit
_results1 = []
$(el).css('font-size', `${options.maxFontSize || 60}px`)
var originalClientHeight = getHeightWithoutPadding(el.parentNode)
var minFontSize = options.minFontSize || 9
while (
el.scrollHeight > originalClientHeight &&
getFontSize(el) > minFontSize
) {
_results1.push(resizeText())
}
return _results1
})(el)
)
}
return $(this)
}
return $
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment