이번에는 구글의 검색 결과 창으로 이동하는 기능을 개발해보겠습니다.
먼저 저번시간에 작성했던 html 코드의 today-info div태그아래에 다음 코드를 추가해줍니다.
<div class="search">
<input id="search-input" placeholder="검색어를 입력하세요" />
</div>
코드를 저장하고 실행해보면
화면에 "검색어를 입력하세요"라는 글자가 적힌 input폼이 나타납니다.
이전에 검색했던 기록들이 나오면 input태그에 autocomplete속성을 off로 설정해줍니다.
이제 search.js라는 파일을 하나 만들고 위의 input요소를 가져오겠습니다.
const searchInput = document.getElementById("search-input");
그 다음, 우리는 이 input 폼에 검색어를 입력하고 엔터를 누르면, 그 값을 검색한 결과 페이지로 이동시켜야하는 기능을 만들어야하기 때문에,
우선 showSearchResult 라는 함수 안에 searchWord 라는 변수를 선언하고 searchInput 요소에 입력된 값을 할당해준 다음
const searchInput = document.getElementById("search-input");
const showSearchResult = () => {
let searchWord = searchInput.value;
};
구글 검색창에 들어가 아무거나 입력해보면 “ https://www.google.com/search?q= ” 뒤에 검색어가 적혀있는 주소로 이동하는 것을 알 수 있습니다.
window의 location.href를 이용하면, 특정 주소로 이동할 수 있습니다.
const searchInput = document.getElementById("search-input");
const showSearchResult = () => {
let searchWord = searchInput.value;
window.location.href = `https://google.com/search?q=${searchWord}`;
searchWord = "";
};
이제 엔터를 눌렀을 때 이 함수가 실행될 수 있도록 해보겠습니다.
enterkey라는 함수를 생성하고, 매개변수로는 event를 받아 이 event의 코드가 Enter라면 함수를 실행합니다.
const searchInput = document.getElementById("search-input");
const showSearchResult = () => {
let searchWord = searchInput.value;
window.location.href = `https://google.com/search?q=${searchWord}`;
searchWord = "";
};
const enterKey = (event) => {
if (event.code === "Enter") {
showSearchResult();
}
};
enterKey 함수의 매개변수인 event는 searchInput에 addEventListener를 사용해,
특정 키를 누르는 이벤트인 "keypress"를 통해 받아올 수 있습니다ㅣ.
이 addEventListener에 작성되는 함수의 매개변수로 event를 받고, 이 event를 enterKey 함수에 인수로 전달해주면,
우리가 누르는 키가 event로 넘겨져, 누르는 키가 enter key라면 showSearchResult 함수를 실행시켜
입력한 검색어를 검색한 결과페이지로 이동시킬 수 있습니다.
searchInput.addEventListener("keypress", (event) => {
enterKey(event);
});
검색결과 잘 이동함을 알 수 있습니다.
css
검색바의 css 스타일입니다.
/* 검색 */
.main-wrapper .search {
display: flex;
justify-content: center;
}
.main-wrapper #search-input {
background-color: rgba(0, 0, 0, 0.5);
color: white;
font-size: var(--medium);
padding: 15px 0px;
border-radius: 30px;
border: 0px;
width: 600px;
text-align: center;
margin-top: -15px;
}
마지막으로 placeholder인 "검색어를 입력하세요"의 스타일을 설정해주겠습니다.
.main-wrapper #search-input::placeholder {
color: rgb(169, 169, 169);
font-size: var(--medium);
}
결과화면
참고자료
'프론트엔드 > javascript' 카테고리의 다른 글
자바스크립트 - 5. 북마크 바 만들기 (0) | 2023.06.11 |
---|---|
javascript - 4. 명언 설정하기 (0) | 2023.06.11 |
javascript - 2. 시계만들기 (0) | 2023.06.10 |
javascript - 1.크롬시작화면만들기 (0) | 2023.06.10 |
javascript - localStorage로 데이터 저장 (0) | 2023.06.08 |