Notice
Recent Posts
Recent Comments
Link
SeouliteLab
jQuery .focus() 메서드 이해하기: 요소에 포커스 주기 본문
focus()
메서드는 jQuery에서 사용되며, 선택한 요소에 포커스를 설정합니다. 이를 통해 사용자 경험을 향상시키고 사용자가 원하는 요소에 빠르게 포커스를 이동할 수 있습니다.
예제 1: 입력 필드에 포커스 주기
<!DOCTYPE html>
<html>
<head>
<title>jQuery .focus() 메서드 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("#username").focus();
});
</script>
</head>
<body>
<input type="text" id="username" placeholder="이름을 입력하세요">
</body>
</html>
설명: 이 예제에서는 페이지가 로드될 때 자동으로 입력 필드에 포커스가 주어집니다.
예제 2: 버튼 클릭 시 입력 필드에 포커스 주기
<!DOCTYPE html>
<html>
<head>
<title>jQuery .focus() 메서드 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("#focusButton").click(function(){
$("#email").focus();
});
});
</script>
</head>
<body>
<input type="email" id="email" placeholder="이메일을 입력하세요">
<button id="focusButton">포커스 주기</button>
</body>
</html>
설명: 이 예제에서는 버튼을 클릭하면 이메일 입력 필드에 포커스가 주어집니다.
예제 3: 입력 필드에 포커스를 주고 특정 이벤트 발생 시 알림 출력
<!DOCTYPE html>
<html>
<head>
<title>jQuery .focus() 메서드 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("#password").focus(function(){
alert("비밀번호 입력 필드에 포커스가 주어졌습니다.");
});
});
</script>
</head>
<body>
<input type="password" id="password" placeholder="비밀번호를 입력하세요">
</body>
</html>
설명: 이 예제에서는 페이지가 로드될 때 비밀번호 입력 필드에 포커스가 주어지면 알림이 표시됩니다.
예제 4: 입력 필드에 포커스를 주고 키 입력 이벤트 처리
<!DOCTYPE html>
<html>
<head>
<title>jQuery .focus() 메서드 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("#search").focus(function(){
alert("검색어를 입력하세요.");
});
$("#search").keyup(function(){
alert("검색 중...");
});
});
</script>
</head>
<body>
<input type="text" id="search" placeholder="검색어를 입력하세요">
</body>
</html>
설명: 이 예제에서는 검색 입력 필드에 포커스가 주어지면 "검색어를 입력하세요" 알림이 표시되고, 키를 입력할 때마다 "검색 중..." 알림이 표시됩니다.
예제 5: 입력 필드에 포커스 주고 특정 조건일 때 다른 요소에 포커스 주기
<!DOCTYPE html>
<html>
<head>
<title>jQuery .focus() 메서드 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("#username").focus(function(){
var username = $(this).val();
if(username === ""){
$("#username").focus();
} else {
$("#password").focus();
}
});
});
</script>
</head>
<body>
<input type="text" id="username" placeholder="아이디를 입력하세요">
<input type="password" id="password" placeholder="비밀번호를 입력하세요">
</body>
</html>
설명: 이 예제에서는 페이지 로드 시 아이디 입력 필드에 포커스가 주어지고, 아이디를 입력하면 자동으로 비밀번호 입력 필드에 포커스가 이동됩니다.
'프로그래밍' 카테고리의 다른 글
jQuery .focusout() 메서드 이해하기: 요소가 포커스를 잃었을 때 처리하기 (0) | 2024.04.03 |
---|---|
jQuery .focusin() 메서드 이해하기: 요소에 포커스가 들어왔을 때 처리하기 (0) | 2024.04.03 |
jQuery focus 이벤트 이해하기: 요소에 포커스가 들어왔을 때 처리하기 (0) | 2024.04.03 |
jQuery event.which 속성 이해하기: 키 코드 식별하기 (0) | 2024.04.03 |
jQuery event.type 속성 이해하기: 이벤트 유형 식별하기 (0) | 2024.04.03 |