-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.textchange.js
85 lines (69 loc) · 2.06 KB
/
jquery.textchange.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
/*!
* jQuery TextChange Plugin
* http://www.zurb.com/playground/jquery-text-change-custom-event
*
* Origin:
* Copyright 2010, ZURB
* Released under the MIT License
*/
(function ($) {
$.fn.hasContentEditable = function() {
return this[0].contentEditable === 'true';
};
$.event.special.textchange = {
setup: function (data, namespaces) {
var $this = $(this);
$this.data('lastValue', $this.hasContentEditable() ? $this.html() : $this.val())
.on('keyup.textchange', $.event.special.textchange.handler)
.on('cut.textchange paste.textchange input.textchange', $.event.special.textchange.delayedHandler);
},
teardown: function (namespaces) {
$(this).off('textchange');
},
handler: function (event) {
$.event.special.textchange.triggerIfChanged($(this));
},
delayedHandler: function (event) {
var $this = $(this);
setTimeout(function () {
$.event.special.textchange.triggerIfChanged($this);
}, 25);
},
triggerIfChanged: function (element) {
var current = element.hasContentEditable() ? element.html() : element.val();
if (current !== element.data('lastValue')) {
element.trigger('textchange', [element.data('lastValue')]);
element.data('lastValue', current);
}
}
};
$.event.special.hastext = {
setup: function (data, namespaces) {
$(this).on('textchange', $.event.special.hastext.handler);
},
teardown: function (namespaces) {
$(this).off('textchange', $.event.special.hastext.handler);
},
handler: function (event, lastValue) {
var $this = $(this);
if (lastValue === '' && lastValue !== $this.val()) {
$this.trigger('hastext');
}
}
};
$.event.special.notext = {
setup: function (data, namespaces) {
$(this).on('textchange', $.event.special.notext.handler);
},
teardown: function (namespaces) {
$(this).off('textchange', $.event.special.notext.handler);
},
handler: function (event, lastValue) {
var $this = $(this),
value = $this.val();
if (value === '' && value !== lastValue) {
$this.trigger('notext');
}
}
};
})(jQuery);