-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfitText.js
More file actions
104 lines (85 loc) · 2.73 KB
/
fitText.js
File metadata and controls
104 lines (85 loc) · 2.73 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
function fitText( arg ) {
var defaults = {
selector: '[data-fittext]',
wrap: true,
sizes: {
min: 10,
max: 40
}
};
var options;
if ( typeof arg === 'undefined' ){
options = defaults;
} else if ( typeof arg === 'string' ){
options = {...defaults, selector: arg};
} else {
options = {...defaults, arg}
}
if( options.selector === null ){
return;
}
var elements = document.querySelectorAll(options.selector);
elements.forEach( (item, index)=>{
var itemOptions
if(item.dataset.fittext){
itemOptions = {...options,
sizes: {
min: item.dataset.fittextSizeMin,
max: item.dataset.fittextSizeMax
}
}
} else{
itemOptions = options;
}
if(item.dataset.fittextLive == 'true' && !item.dataset.fittextobservable){
item.dataset.fittext = "fittext-"+index;
item.dataset.fittextobservable = true;
window.addEventListener('resize',debounce(function(){
fitText('[data-fittext="fittext-'+index+'"]')
}, 100));
}
var originalWordBreak = item.style.wordBreak;
item.style.fontSize = itemOptions.sizes.max + "px";
item.style.wordBreak = 'break-all';
if( itemOptions.wrap ){
var longest = 0;
var longestIndex = 0;
item.innerHTML = item.innerHTML.split(' ').map((word, index, words)=>{
if(index > 0 && word.length > words[longestIndex].length) {
longestIndex = index;
longest = word.length;
}
return "<div>"+word+"</div>";
}).join(' ');
var controlWord = item.querySelectorAll('div')[longestIndex];
reduceFont( controlWord, item, options, function(){
item.innerHTML = item.textContent || item.innerText;
item.style.wordBreak = originalWordBreak;
});
} else {
reduceFont( item, item, options, function(){ });
}
} );
}
fitText();
// helpers
function reduceFont(control, element, options, cb) {
var fontSize = parseInt(element.style.fontSize);
var decrement = Math.ceil(fontSize/20);
if(
fontSize > options.sizes.min &&
control.getBoundingClientRect().height > 2*fontSize
){
element.style.fontSize = fontSize-decrement+'px';
reduceFont(control, element, options, cb);
}else{
cb();
}
}
function debounce(cb, ms) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(cb.bind(this), ms, ...args);
};
}