[jQuery] delayKeyStroke
[jQuery] delayKeyStroke
Hi!
This morning i wrote a lite plugin that i would like to share, i call it delayKeyStroke.
I'm using it on a input box for a auto complete function that makes Ajax calls to a server.
The function has 4 required params.
timer = time i seconds between keystrokes before the script thinks that he/her has finished
minChar = minimum input chars before onSuccess is fired
onSuccess = function for handling if above is true.
onEmpty = function that fires if the input length equals 0.
$("input#q").delayKeyStroke(timer,minChars,onSuccess,onEmpty});
Testing, thought and so on are very much appreciated!
Best regards
Christian Bach
And finaly the code:
<script>
$.fn.delayKeyStroke = function(time,minChars,callOpen,callClose) {
return this.each(function(){
var t = new $.delayKeyStrokeCounter(time,callOpen);
$(this).keyup(function() {
if($(this).val().length >= minChars) {
t.setStamp();
} else if($(this).val().length == 0) {
callClose();
}
});
});
};
$.delayKeyStrokeCounter = function(iTrigger,oCall) {
var iTime = 0;
var iTrigger = iTrigger;
var oCall = oCall;
var iStamp = 0;
var o = this;
var state = 'none';
var timer = null;
timer = setInterval( function(){if(state == 'stamped') {o.updateTimer();}}, 1000 );
this.getTimer = function() {return iTime};
this.getStamp = function() {return iStamp};
this.setStamp = function() {iStamp = this.getTimer(); state = 'stamped'};
this.updateTimer = function() {iTime++; this.checkStamp();};
this.checkStamp = function() {if((this.getTimer() - this.getStamp()) >= iTrigger){oCall();this.reset();}};
this.reset = function() {state = 'none'; iTime = 0; iStamp = 0;};
};
</script>
<script>
$(document).ready(function() {
$("input#q").delayKeyStroke(2,3,function() {
$("div#auto-complete").html("key strokes has fired...");
$("div#auto-complete").fadeIn('fast');
},function() {
$("div#auto-complete").fadeOut('fast');
});
});
</script>
_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/