Skip to content

Instantly share code, notes, and snippets.

@shuuuuun
Last active January 14, 2016 13:03
Show Gist options
  • Save shuuuuun/b568d6af658431dddf02 to your computer and use it in GitHub Desktop.
Save shuuuuun/b568d6af658431dddf02 to your computer and use it in GitHub Desktop.
inputを監視するやつ。 demo: http://jsdo.it/shuuuuun/oLhy
function setInputWatcher($target, interval, execFn){
var timer;
$target.on("focus", onFocusFn);
$target.on("blur", onBlurFn);
function onFocusFn(){
clearInterval(timer);
var prevVal = $target.val();
timer = setInterval(function(){
var newVal = $target.val();
if (newVal !== prevVal) {
execFn(newVal, prevVal);
}
prevVal = newVal;
}, interval);
}
function onBlurFn(){
clearInterval(timer);
}
}
// ex ---
var $input = $("#input");
setInputWatcher($input, 500, function(val){
console.log(val);
});
function setInputWatcher(target, interval, execFn){
var timer;
target.addEventListener("focus", onFocusFn, false);
target.addEventListener("blur", onBlurFn, false);
function onFocusFn(){
clearInterval(timer);
var prevVal = target.value;
timer = setInterval(function(){
var newVal = target.value;
if (newVal !== prevVal) {
execFn(newVal, prevVal);
}
prevVal = newVal;
}, interval);
}
function onBlurFn(){
clearInterval(timer);
}
}
// ex ---
var input = document.getElementById("input");
setInputWatcher(input, 500, function(val){
console.log(val);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment