forked from janesmae/editableText
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.editableText.js
103 lines (93 loc) · 2.72 KB
/
jquery.editableText.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
92
93
94
95
96
97
98
99
100
101
102
103
/**
* editableText plugin that uses contentEditable property (FF2 is not supported)
* Project page - http://github.com/valums/editableText
* Copyright (c) 2009 Andris Valums, http://valums.com
* Licensed under the MIT license (http://valums.com/mit-license/)
*/
(function(){
/**
* The dollar sign could be overwritten globally,
* but jQuery should always stay accesible
*/
var $ = jQuery;
/**
* Extending jQuery namespace, we
* could add public methods here
*/
$.editableText = {};
$.editableText.defaults = {
/**
* Pass true to enable line breaks.
* Useful with divs that contain paragraphs.
*/
newlinesEnabled : false,
/**
* Event that is triggered when editable text is changed
*/
changeEvent : 'change'
};
/**
* Usage $('selector).editableText(optionArray);
* See $.editableText.defaults for valid options
*/
$.fn.editableText = function(options){
var options = $.extend({}, $.editableText.defaults, options);
return this.each(function(){
// Add jQuery methods to the element
var editable = $(this);
/**
* Save value to restore if user presses cancel
*/
var prevValue = editable.html();
// Create edit/save buttons
var buttons = $(
"<div class='editableToolbar'>" +
"<a href='#' class='edit'></a>" +
"<a href='#' class='save'></a>" +
"<a href='#' class='cancel'></a>" +
"</div>")
.insertBefore(editable);
// Save references and attach events
var editEl = buttons.find('.edit').click(function() {
startEditing();
return false;
});
buttons.find('.save').click(function(){
stopEditing();
editable.trigger(options.changeEvent);
return false;
});
buttons.find('.cancel').click(function(){
stopEditing();
editable.html(prevValue);
return false;
});
// Display only edit button
buttons.children().css('display', 'none');
editEl.show();
if (!options.newlinesEnabled){
// Prevents user from adding newlines to headers, links, etc.
editable.keypress(function(event){
// event is cancelled if enter is pressed
return event.which != 13;
});
}
/**
* Makes element editable
*/
function startEditing(){
buttons.children().show();
editEl.hide();
editable.attr('contentEditable', true);
}
/**
* Makes element non-editable
*/
function stopEditing(){
buttons.children().hide();
editEl.show();
editable.attr('contentEditable', false);
}
});
}
})();