-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathcontentEditable.js
78 lines (63 loc) · 1.95 KB
/
contentEditable.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
// jQuery contentEditable() plugin
//
// Created by: Makis Tracend (@tracend)
// Issue: http://stackoverflow.com/a/6263537
//
// Licensed under the GPL Version 2: http://www.gnu.org/licenses/gpl-2.0.html
(function( $ ){
var methods = {
init : function( options ) {
return this.each(function(){
var $this = $(this);
//reset any previous change events set
$this.unbind("change");
$this.find('[contenteditable]').each(function(){
$(this).contentEditable("field", $this);
});
});
},
field : function( parent ) {
return this.each(function(){
var $this = $(this);
// setting the key based on an attribute available on the same level as 'contentEditable'
var key = $this.attr("data-key");
// add triggers
$this.live('focus', function() {
var $this = $(this);
$this.data('enter', $this.html());
$this.data('before', $this.html());
return $this;
}).live('keyup paste', function() {
var $this = $(this);
var text = $this.html();
if ($this.data('before') !== text) {
$this.data('before', text);
var data = {};
data[key] = text;
parent.trigger({type: 'change', action : 'update', changed: data});
}
return $this;
}).live('blur', function() {
var $this = $(this);
var text = $this.html();
if ($this.data('enter') !== text) {
$this.data('enter', text);
var data = {};
data[key] = text;
parent.trigger({type: 'change', action : 'save', changed: data});
}
return $this;
})
});
}
};
$.fn.contentEditable = function( method ) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.contentEditable' );
}
};
})( jQuery );