Jquery plugin for Edit at place

Luckychap 0 Tallied Votes 359 Views Share

This is Jquery plugin which can be used to change the content a its place.
Features:
1. Easy to use
2. Maintain changeability of Jquery

Know Issue:
1. Can take html string also as input

For example:

html:

<div id="editable">I can be changed right here</div>

javascript:

$.('#editable').editAtPlace(function(newtext, oldtext) {
    alert("Old Text: " + oldtext + "  New Text: " + newtext);
});
/* Plugin code starts here */
(function($) {
	$.fn.editAtPlace = function(callback) {
		return this.each(function() {
			var clickFn = function(){
				var el = $(this);
				var pHtml = el.html();
				var nHtml = "<input id='editInPlaceText' type='text' value='" + pHtml + "'></input>";
				$(this).html(nHtml);

				var onComplete = function(newText) {
					if(callback) {
						el.html(newText);
						el.bind('click', clickFn);
						callback(newText, pHtml);
					}
				};
				// On Focus of text box, unbind the click event for el
				$('#editInPlaceText').focusin(function() {
					el.unbind('click', clickFn);
				});
				// For ENTER key, bind click event to el again and call the callback function
				$('#editInPlaceText').keyup(function(e) {
					if(e.keyCode == 13) {
						var value = e.target.value;
						onComplete(value);
					}
				});
				// On Foucus out of text box, bind click event to el again and call the callback function
				$('#editInPlaceText').focusout(function(e) {
					var value = e.target.value;
					onComplete(value);
				});
				// Give focus to new text box
				$('#editInPlaceText').focus();
			}
			$(this).bind("click", clickFn);
		});
	}
})(jQuery); /* Plugin code ends */



/* USAGE */
// For all the divs
$('div').editAtPlace(function(newText, oldText) {
	alert("<div> : " + newText);
});
// For all the spans
$('span').editAtPlace(function(newText, oldText) {
	alert("<span> : " + newText);
});
// For element with id 'text3'
$('#text3').editAtPlace(function(newText, oldText) {
	alert("<p> with id 'text3': " + newText);
});