방향키와 페이지 업다운 키를 이용하여 포커스 이동을 구현해보았다.

<!doctype html>
<html lang="ko">
<head>
	<meta charset="utf-8">
	<title>키보드를 이용한 포커스 이동</title>
</head>
<body>
	<h1>키보드로 이동하기</h1>
	
	<form name="frm">
		<input name="a"><input name="b"><input name="c"><br>
		<input name="a"><input name="b"><input name="c"><br>
		<input name="a"><input name="b"><input name="c"><br>
		<input name="a"><input name="b"><input name="c"><br>
		<input name="a"><input name="b"><input name="c"><br>
		<input name="a"><input name="b"><input name="c"><br>
		<input name="a"><input name="b"><input name="c"><br>
		<input name="a"><input name="b"><input name="c"><br>
		<input name="a"><input name="b"><input name="c"><br>
		<input name="a"><input name="b"><input name="c"><br>
		<input name="a">
		
		<button>전송</button>
	</form>
	
	
</body>
<script>
	const inputs = document.querySelectorAll("input");
	const total = inputs.length;

	const cols = 3; // 컬럼수
	//const rows = Math.ceil(total/cols); // 줄수

	function keyevent(event) {
		const keycode = event.keyCode;
		const idx = Array.from(document.querySelectorAll('input')).indexOf(event.target);

		switch (keycode) {
			case (13) : // Enter
				if(idx===(total-1)){ //enter      
					//alert("폼 전송");
				}else{
					document.querySelectorAll('input')[idx+1].focus();
				}
				break;

			case(33) : // PageUp
				document.querySelectorAll('input')[0].focus();
				break;

			case(34) : // PageDown
				document.querySelectorAll('input')[total-1].focus();
				break;
			case(37) : // Left
				if(idx===0){
					return false;      
				}else{  
					document.querySelectorAll('input')[idx-1].focus();
				}
				break;
			case(38) : // Up
				if(idx < cols){
					return false;      
				}else{
					document.querySelectorAll('input')[idx-cols].focus();
				} 
				break;
			case(39) : // Right
				if(idx===(total-1)){ 
					return false;      
				}else{      
					document.querySelectorAll('input')[idx+1].focus();
				} 
				break;

			case (40) : // Down
				if(idx+cols >= total){
					return false;       
				}else{
					document.querySelectorAll('input')[idx+cols].focus();
				}
				break;

			default : 
				return false;
				break;
		}
	}


	
	function formCheck(e) {
		// 문제가 있으면
		// e.preventDefault();
	}
	
	document.querySelector("form").addEventListener('submit', formCheck);
	for(const item of inputs) {
		item.addEventListener('keydown', keyevent);
	}

</script>
</html>

 

 

'Javascript' 카테고리의 다른 글

정렬 sort  (0) 2021.04.01
jQuery to VanillaJS  (0) 2021.03.16
String to Date / Date to String  (0) 2020.12.17
숫자에 콤마와 언콤마를 편하게  (0) 2016.06.27
정규식으로 괄호 안의 문자 추출과 치환하기  (0) 2015.07.09

+ Recent posts