-
Notifications
You must be signed in to change notification settings - Fork 2
/
jquery.inputfit.js
68 lines (55 loc) · 2.26 KB
/
jquery.inputfit.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
/*global define:true */
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
$.fn.inputfit = function(options) {
var settings = $.extend({
minSize : 10,
maxSize : false
}, options);
this.each(function() {
var $input = $(this);
if ( !$input.is(':input') ) {
return;
}
$input.off('keyup.inputfit keydown.inputfit');
var maxSize = parseFloat(settings.maxSize || $input.css('font-size'), 10);
var width = $input.width();
var clone = $input.data('inputfit-clone');
if (!clone) {
clone = $('<div></div>', {
css : {
fontSize : $input.css('font-size'),
fontFamily : $input.css('font-family'),
fontStyle : $input.css('font-style'),
fontWeight : $input.css('font-weight'),
fontVariant : $input.css('font-variant'),
letterSpacing: $input.css('letter-spacing'),
position : 'absolute',
left : '-9999px',
visibility : 'hidden'
}
}).insertAfter($input);
$input.data('inputfit-clone', clone);
}
$input.on('keyup.inputfit keydown.inputfit', function() {
var $this = $(this);
clone.html($this.val().replace(/ /g, ' '));
var ratio = width / (clone.width() || 1),
currentFontSize = parseInt( $this.css('font-size'), 10 ),
fontSize = Math.floor(currentFontSize * ratio);
if (fontSize > maxSize) { fontSize = maxSize; }
if (fontSize < settings.minSize) { fontSize = settings.minSize; }
$this.css('font-size', fontSize);
clone.css('font-size', fontSize);
}).triggerHandler('keyup.inputfit');
});
return this;
};
}));