forked from davatron5000/FitText.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.fittext.js
92 lines (85 loc) · 2.51 KB
/
jquery.fittext.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Generated by CoffeeScript 1.6.2
/*!
FitText.js 1.1
Copyright 2011, Dave Rupert http://daverupert.com
Released under the WTFPL license
http://sam.zoy.org/wtfpl/
*/
(function($) {
var DEFAULT_OPTIONS, debounce, forceFloat;
DEFAULT_OPTIONS = {
minFontSize: Number.NEGATIVE_INFINITY,
maxFontSize: Number.POSITIVE_INFINITY,
compressorScale: 10,
preserveLineHeight: true,
debounce: 100
};
forceFloat = function(value, fallback) {
if (fallback == null) {
fallback = 0;
}
value = parseFloat(value);
if (isNaN(value)) {
return fallback;
} else {
return value;
}
};
debounce = function(fn, wait) {
var result, timeout;
timeout = null;
result = null;
return function() {
var args, context, later;
context = this;
args = arguments;
later = function() {
timeout = null;
return result = fn.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
return result;
};
};
$.fn.fitText = function(compressor, options) {
if (compressor == null) {
compressor = 1;
}
if (options == null) {
options = {};
}
options = $.extend({}, DEFAULT_OPTIONS, options);
options.minFontSize = forceFloat(options.minFontSize, DEFAULT_OPTIONS.minFontSize);
options.maxFontSize = forceFloat(options.maxFontSize, DEFAULT_OPTIONS.maxFontSize);
compressor *= options.compressorScale;
return this.each(function() {
var $this, lineHeight, resizer;
$this = $(this);
lineHeight = forceFloat($this.css('line-height')) / forceFloat($this.css('font-size'));
resizer = function() {
var fontSize;
fontSize = $this.width() / compressor;
fontSize = Math.max(Math.min(fontSize, options.maxFontSize), options.minFontSize);
$this.css('font-size', fontSize);
if (options.preserveLineHeight && lineHeight > 0) {
return $this.css('line-height', "" + (fontSize * lineHeight) + "px");
}
};
$(window).on('resize.fitText', debounce(resizer, options.debounce));
return resizer();
});
};
return $(function() {
return $('[data-fit-text]').each(function() {
var $this, compressor, options;
$this = $(this);
compressor = $this.attr('data-fit-text') || 1;
options = {
minFontSize: $this.attr('data-min-font-size'),
maxFontSize: $this.attr('data-max-font-size')
};
return $this.fitText(compressor, options);
});
});
})(jQuery);