shuuuuun
1/14/2016 - 12:13 PM

inputを監視するやつ。 demo: http://jsdo.it/shuuuuun/oLhy

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);
});