![[JS] Input이 활성화 될 때, 커서 자동 Focus 하는 방법 [JS] Input이 활성화 될 때, 커서 자동 Focus 하는 방법](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
Auto Focus
Display:none인 <Input>
태그가 포함된 요소가 JS
를통해 나타나게 해줬을때 커서가 자동으로 input
에 foucs
되게 하는 방법에 대해 알아 보겠습니다.
Input 생성
우선 텍스트를 입력할 수 있는 <input>
태그를 생성해줍니다.
<form> <div class="container"> <div> <input placeholder="검색어를 업력하세요"> <button><i class="fa-solid fa-magnifying-glass"></i></button> </div> </div> </form>
![[JS] Input이 활성화 될 때, 커서 자동 Focus 하는 방법 - Input 생성 [JS] Input이 활성화 될 때, 커서 자동 Focus 하는 방법 - Input 생성](http://t1.daumcdn.net/tistory_admin/static/images/no-image-v1.png)
버튼 클릭 시 input 보이기
위에 만들어놓은 <input>
태그를 display:none
으로 없애준 뒤에, 특정 버튼을 누르면 다시 <input>
이 보이도록 자바스크립트를 통해 코드를 작성합니다.
$(document).ready(function () { var target = $('.container'); $(document).on('click', '.showInput', function (e) { $('.showInput').hide(); target.fadeIn(100).addClass('reveal'); }); $(document).mouseup(function (e) { if (target.has(e.target).length == 0) { target.fadeOut().removeClass('reveal'); setTimeout(() => { $('.showInput').fadeIn(); }, 1000); } }); });
이 코드대로만 실행 된다면, <input>
태그에 커서가 자동으로 Focus
되지 않습니다.
아래 데모를 통해 테스트할 수 있습니다.
AutoFoucs 적용 방법
autoFoucs
적용방법은 의외로 간단합니다. 위 JS
코드에 fadeIn
을 통해 reveal
이라는 클래스를 추가하고 container.reveal
이 되면서 display
가 block
처리되게 해 줬습니다.
이 fadeIn
메서드 안에 새로운 function
을 생성하고 그 안에 .foucs()
메서드를 사용하게 되면 자동으로 커서가 특정 id
값으로 Focus
되게 됩니다.
우선 HTML
의 <input>
태그에 id
값을 focus
로 정해주고 자바스크립트를 아래 처럼 작성해주겠습니다.
<input id="focus" placeholder="검색어를 업력하세요">
target.fadeIn(100, function() { $('#focus').focus(); }).addClass('reveal');
전체 코드로 보자면 아래와 같습니다.
$(document).ready(function () { var target = $('.container'); $(document).on('click', '.showInput', function (e) { $('.showInput').hide(); target.fadeIn(100, function() { $('#focus').focus(); }).addClass('reveal'); }); $(document).mouseup(function (e) { if (target.has(e.target).length == 0) { target.fadeOut().removeClass('reveal'); setTimeout(() => { $('.showInput').fadeIn(); }, 1000); } }); });
아래 데모를 통해 테스트할 수 있습니다.
전체 소스코드
전체 소스코드를 github에도 공유합니다.
GitHub - Seogun95/autoMouseFocusJS
Contribute to Seogun95/autoMouseFocusJS development by creating an account on GitHub....
github.com
오늘은 이렇게 Display
:none
인 <Input>
태그가 포함된 요소가 JS
를 통해 나타나게 해 줬을 때 커서가 자동으로 input
에 foucs
되게 하는 방법에 대해 알아보았습니다.
읽어주셔서 감사합니다🤟
'FRONT-END > JAVASCRIPT' 카테고리의 다른 글
[CSS + JS] 스켈레톤 로딩(Skeleton Loading) - 컨텐츠 모자이크 (1) | 2022.09.16 |
---|---|
[JS] JQuery 윈도우 Event Methods (2) | 2022.09.15 |
[JS] 닫기버튼을 만들어 부모 태그 없애기 (display: none) (1) | 2022.09.13 |
[JS] 오프스크린 이미지를 지연(Lazyload) 로드 - lazysizes (0) | 2022.09.12 |
[JS] 로딩이 될때 요소의 텍스트를 변경하는 방법 (1) | 2022.09.11 |