-
Notifications
You must be signed in to change notification settings - Fork 26
/
jquery.editable.js
91 lines (82 loc) · 2.72 KB
/
jquery.editable.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
86
87
88
89
90
91
// jQuery.editable.js v1.1.2
// http://shokai.github.io/jQuery.editable
// (c) 2012-2015 Sho Hashimoto <[email protected]>
// The MIT License
(function($){
var escape_html = function(str){
return str.replace(/</gm, '<').replace(/>/gm, '>');
};
var unescape_html = function(str){
return str.replace(/</gm, '<').replace(/>/gm, '>');
};
$.fn.editable = function(event, callback){
if(typeof callback !== 'function') callback = function(){};
if(typeof event === 'string'){
var trigger = this;
var action = event;
var type = 'input';
}
else if(typeof event === 'object'){
var trigger = event.trigger || this;
if(typeof trigger === 'string') trigger = $(trigger);
var action = event.action || 'click';
var type = event.type || 'input';
}
else{
throw('Argument Error - jQuery.editable("click", function(){ ~~ })');
}
var target = this;
var edit = {};
edit.start = function(e){
trigger.unbind(action === 'clickhold' ? 'mousedown' : action);
if(trigger !== target) trigger.hide();
var old_value = (
type === 'textarea' ?
target.text().replace(/<br( \/)?>/gm, '\n').replace(/>/gm, '>').replace(/</gm, '<') :
target.text()
).replace(/^\s+/,'').replace(/\s+$/,'');
var input = type === 'textarea' ? $('<textarea>') : $('<input>');
input.val(old_value).
css('width', type === 'textarea' ? '100%' : target.width()+target.height() ).
css('font-size','100%').
css('margin',0).attr('id','editable_'+(new Date()*1)).
addClass('editable');
if(type === 'textarea') input.css('height', target.height());
var finish = function(){
var result = input.val().replace(/^\s+/,'').replace(/\s+$/,'');
var html = escape_html(result);
if(type === 'textarea') html = html.replace(/[\r\n]/gm, '<br />');
target.html(html);
callback({value : result, target : target, old_value : old_value});
edit.register();
if(trigger !== target) trigger.show();
};
input.blur(finish);
if(type === 'input'){
input.keydown(function(e){
if(e.keyCode === 13) finish();
});
}
target.html(input);
input.focus();
};
edit.register = function(){
if(action === 'clickhold'){
var tid = null;
trigger.bind('mousedown', function(e){
tid = setTimeout(function(){
edit.start(e);
}, 500);
});
trigger.bind('mouseup mouseout', function(e){
clearTimeout(tid);
});
}
else{
trigger.bind(action, edit.start);
}
};
edit.register();
return this;
};
})(jQuery);