Last active
December 19, 2015 13:28
-
-
Save ecounysis/5961962 to your computer and use it in GitHub Desktop.
jQuery plugin to make a dom element editableeditable.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($) { | |
$.fn.editable = function (func) { | |
// func returns true or false - if true the dom element is updated and the popup is removed | |
// func can have side effects | |
// depends on shortcut.js and your definition of the "editable-popup" and "bluelink" classes | |
this.css("cursor", "pointer"); | |
this.click(function (evt) { | |
// cleanup | |
$(".editable-popup").remove(); | |
shortcut.remove("Enter"); | |
// | |
var div_id = "_" + Math.floor(Math.random() * 99999999) + "_editable"; | |
var selector = "#" + div_id; | |
var val = $(this).text(); | |
var width = val.length * 1.5; | |
$("body").append("<div id=\"" + div_id + "\" class=\"editable-popup\"/>") | |
$(selector).append("<table><tr><td rowspan=\"2\"><input type=\"text\" size=\"" + width + "\" id=\"input" + div_id + "\" value=\"\"/></td>" + | |
"<td><span class=\"bluelink\" id=\"save" + div_id + "\">Save</span></td></tr>" + | |
"<tr><td><span class=\"bluelink\" id=\"cancel" + div_id + "\">Cancel</span></td></tr></table></div>"); | |
$(selector).css({ | |
"position": "absolute", | |
"left": $(this).offset().left - 5, | |
"top": $(this).offset().top - 17, | |
"z-index": 10, | |
"opacity": 1 | |
}); | |
var remove = function () { | |
$(selector).remove(); | |
}; | |
var that = this; | |
var input_selector = "#input" + div_id; | |
var savefunc = function () { | |
var new_val = $(input_selector).val(); | |
$(that).text(new_val); | |
}; | |
var close_func = function () { | |
var val = $(input_selector).val(); | |
if ((val === undefined) || func(val)) { | |
savefunc(); | |
remove(); | |
return true; | |
} | |
else { | |
return false; | |
} | |
}; | |
shortcut.add("Enter", function () { | |
if (close_func()) { | |
shortcut.remove("Enter"); | |
} | |
}); | |
$("#save" + div_id).click(close_func); | |
$("#cancel" + div_id).click(remove); | |
$("#input" + div_id).focus(); | |
}); | |
}; | |
return this; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment