Skip to content

Instantly share code, notes, and snippets.

@dir01
Created March 20, 2012 09:39
Show Gist options
  • Save dir01/2133462 to your computer and use it in GitHub Desktop.
Save dir01/2133462 to your computer and use it in GitHub Desktop.
Add previews to textareas
(function($) {
$.fn.previewTextareas = function() {
var $el = this;
var run = function(){
var textareas = $('textarea', $el);
textareas.each(initializeTextarea);
};
var initializeTextarea = function(i, textarea) {
textarea = $(textarea);
attachPreviewToTextarea(textarea);
updatePreview(textarea);
bindEvents(textarea);
};
var attachPreviewToTextarea = function(textarea) {
var preview = getPreviewTemplate();
preview.insertAfter(textarea);
textarea.data('preview', preview);
};
var updatePreview = function(textarea) {
var value = textarea.val();
var preview = textarea.data('preview');
preview.html(value);
};
var bindEvents = function(textarea) {
textarea
.change(onEventUpdatePreview)
.keydown(onEventUpdatePreview)
.keypress(onEventUpdatePreview)
.keyup(onEventUpdatePreview)
.bind('cut paste textInput input', onEventUpdatePreview);
};
var onEventUpdatePreview = function(event){
updatePreview($(event.target));
};
var getPreviewTemplate = function() {
return $('<p></p>');
};
run();
return this;
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment