57f954ba5409a6504af785ed8d42e009

Can the following be streamlined? Currently, attaching carriage return detection to fields is done one way and attaching paste detection another. It would be nice to simplify. Uses prototype library. To see demo: http://gregelin.com/studies/study_2008.001.02/

/* 	study_2008.001.02_field_control.js

    See: http://gregelin.com/studies/study_2008.001.02
*/

// Settings
var multiline_threshold = 30;
var trgFields = ['field1','field2'];

// Diagnostic function - Not criticl
function showKeyStrokes(field,unicode) {
    $('active_field').value = field // show character
    $('lastchar_code').value = unicode // show character
    $('lastchar').value = String.fromCharCode(unicode); // show character
}

function setFieldHeight(target,newStyle) {
    $(target).setStyle(newStyle);
}

// Set field heights
function adjustEntryFields() {
    trgFields.each(function(f) { setFieldHeight(f,{height: '10em'}); });
}

var FieldBehavior = Class.create();
FieldBehavior.prototype = {
    initialize: function(field) {
        this.name = field;
        this.field = $(field);
        this.eventHandlers = {
			onKeyUp: this.onKeyUp.bindAsEventListener(this),
		}
        this.enableEventHandlers();
        return this;
    },
    
    enableEventHandlers: function() {
		this.field.observe('keyup',this.eventHandlers.onKeyUp,false);
	},

	onKeyUp: function(e) {
	    var unicode=e.keyCode? e.keyCode : e.charCode;
	    showKeyStrokes(this.name,unicode);
	    if (unicode == 13) adjustEntryFields(); // if return detected
	    if (e.target.value.length > multiline_threshold) adjustEntryFields(); // if length exceeds threshold
	},
	
};

// Apply behavior to fields
trgFields.each(function(f) { new FieldBehavior(f) });

// Register paste event to text fields. Use prototype.each().
trgFields.each(function(f) {
    $(f).onpaste = pasteAction;
    if ($(f).captureEvents) $(f).captureEvents(Event.PASTE);
});

function pasteAction(e) {
   if (!e) var e = window.event;
    var targ;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
    gtarg = targ; // make global object in order for timeout to understand it
    
    // like to detect if there is a return character and then make field larger
    //var regex = /first/;
    //if (regex.test("first test")) alert('match');
    // setTimeout('alert("timeout")',50);
    
    adjustEntryFields();
}

Refactorings

No refactoring yet !

Your refactoring





Format Copy from initial code

or Cancel