javascript - JQuery merge two functions keyup and focusout -
on form-field work 2 active functions: keyup , focusout. functions execute same code, key-up uses delay-function.
function delay:
$(function() { var delay = (function(){ var timer = 0; return function(callback, ms){ cleartimeout (timer); timer = settimeout(callback, ms); }; })();
functions keyup , focusout:
$("#name").on('keyup', function (){ var textn = $(this).val(); var nbrcharn = textn.length; delay(function(){ if(nbrcharn > '2'){ $('#namemsg').html('nice.'); }else { $('#namemsg').html(''); } }, 1000 ); }); $("#name").on('focusout', function (){ var textn = $(this).val(); var nbrcharn = textn.length; if(nbrcharn > '2'){ $('#namemsg').html('nice.'); }else { $('#namemsg').html(''); } });
the keyup needs delay, focusout not. code works fine, possible merge functions, don't have same code twice?
you define handler takes argument completion function
var handler = function (completion){ return function(){ var textn = $(this).val(), nbrcharn = textn.length; completion(function(){ if(nbrcharn > '2'){ $('#namemsg').html('nice.'); } else { $('#namemsg').html(''); } }); }; };
and define handlers
$("#name").on('keyup',handler(function(cb){delay(cb,1000);})); $("#name").on('focusout',handler(function(cb){cb();}));