forked from dustinhayes/typecount
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypecount.js
More file actions
74 lines (57 loc) · 2.15 KB
/
typecount.js
File metadata and controls
74 lines (57 loc) · 2.15 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
(function ( win, doc ) {
'use strict';
$.fn.nextOf = function( selector ) {
return this.nextAll( selector ).first();
};
var $typecounters = $( '[data-typecount]' ),
defaults = {
min: 5,
max: 20,
warn: 5
},
publish = function( fn ) {
var $this = this,
counter = function( event ) {
var count = $this.val().length;
fn.call( $this, count, event );
};
$this.on( 'keydown keyup', counter );
},
update = function( settings ) {
var $this = this,
setHTML = function( count ) {
var $target = $this.nextOf('.count'),
remaining = settings.max - count,
message = remaining + ' characters remaining';
if ( count >= settings.min )
$target.text( message );
else
$target.empty();
if ( remaining <= settings.warn )
$target.addClass('warn');
else
$target.removeClass('warn');
};
publish.call( $this, setHTML );
},
restrict = function( settings ) {
var $this = this,
prevent = function ( count, event ) {
var noprintKeys = /^8$|^9$|^16$|^18$|^20$|^17$|^37$|^38$|^39$|^40$|^93$/;
if ( count >= settings.max )
if ( ! noprintKeys.test( event.keyCode ) )
event.preventDefault();
};
publish.call( $this, prevent );
},
oneach = function( index, element ) {
var $element = $( element ),
data = $element.data( 'typecount' ),
settings = $.extend( {}, defaults, data );
update.call( $element, settings );
restrict.call( $element, settings );
};
if ( $typecounters.length === 0 )
return;
$.each( $typecounters, oneach );
}( window, document ));