안녕하세요 오늘도 자스 연습을 해보도록 하겠습니다
5일차는 너무 CSS중점적이라서 건너뛰게 되었습니다.
JavaScript 30
Build 30 things with vanilla JS in 30 days with 30 tutorials
javascript30.com
목차 바로가기
1. 오늘의 과제는? |
2. 어떻게 완성되었는가 |
3. 배운 점 & 느낀 점 |
1. 오늘의 과제는?
사진에서 보시는 바와 같이 검색창에서 단어를 검색하면 그 와 관련된 도시와 주의 이름을 나타내고 오른쪽에서 유명도(?)를 나타냅니다.
시작파일은 이러합니다.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Type Ahead 👀</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form class="search-form">
<input type="text" class="search" placeholder="City or State">
<ul class="suggestions">
<li>Filter for a city</li>
<li>or a state</li>
</ul>
</form>
<script>
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
</script>
</body>
</html>
CSS
html {
box-sizing: border-box;
background: #ffc600;
font-family: 'helvetica neue';
font-size: 20px;
font-weight: 200;
}
*, *:before, *:after {
box-sizing: inherit;
}
input {
width: 100%;
padding: 20px;
}
.search-form {
max-width: 400px;
margin: 50px auto;
}
input.search {
margin: 0;
text-align: center;
outline: 0;
border: 10px solid #F7F7F7;
width: 120%;
left: -10%;
position: relative;
top: 10px;
z-index: 2;
border-radius: 5px;
font-size: 40px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.12), inset 0 0 2px rgba(0, 0, 0, 0.19);
}
.suggestions {
margin: 0;
padding: 0;
position: relative;
/*perspective: 20px;*/
}
.suggestions li {
background: white;
list-style: none;
border-bottom: 1px solid #D8D8D8;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.14);
margin: 0;
padding: 20px;
transition: background 0.2s;
display: flex;
justify-content: space-between;
text-transform: capitalize;
}
.suggestions li:nth-child(even) {
transform: perspective(100px) rotateX(3deg) translateY(2px) scale(1.001);
background: linear-gradient(to bottom, #ffffff 0%,#EFEFEF 100%);
}
.suggestions li:nth-child(odd) {
transform: perspective(100px) rotateX(-3deg) translateY(3px);
background: linear-gradient(to top, #ffffff 0%,#EFEFEF 100%);
}
span.population {
font-size: 15px;
}
.hl {
background: #ffc600;
}
2. 어떻게 완성되었는가
자바스크립트 중점으로 어떻게 애플리케이션이 만들어지는지 봅시다.
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
const cities = [];
먼저 endpoint상수에 api 주소를 저장했고 cities 배열을 선언했습니다.
fetch(endpoint)
.then(blob => blob.json())
.then(data => cities.push(...data));
그리고 fetch함수를 통해서 직접 해당 주소로 통신을 할 수 있습니다. 따라서 response를 얻어내는데 성공했다면 그 값을 json화 하고 json화 된 data를 아까 선언한 cities배열에 push를 하는 것을 볼 수 있습니다.
따라서 cities에 실제 도시와 관련된 많은 정보들이 담겨지게 되었습니다.
function findMatches(wordToMatch, cities) {
return cities.filter(place => {
const regex = new RegExp(wordToMatch, 'gi');
return place.city.match(regex) || place.state.match(regex);
});
}
입력값으로 준 단어와 조금이라도 일치하는 도시들의 배열을 반환한다.
function displayMatches() {
const matchArray = findMatches(this.value, cities);
const html = matchArray.map(place => {
const regex = new RegExp(this.value, 'gi');
const cityName = place.city.replace(regex, `<span class="h1">${this.value}</span>`);
const stateName = place.state.replace(regex, `<span class="h1">${this.value}</span>`);
return `
<li>
<span class="name">${cityName}, ${stateName}</span>
<span class="population">${place.population}</span>
</li>
`;
}).join('');
suggestions.innerHTML = html;
}
입력값으로 준 단어와 일치되는 도시들의 배열을 matchArray에 저장한다.
그리고 map()메서드를 활용해서 matchArray를 돌면서 새로운 배열을 만든다.
html 정보를 담은 html변수를 suggestions의 innerHTML에 넣는다.
const searchInput = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');
searchInput.addEventListener('change', displayMatches);
searchInput.addEventListener('keyup', displayMatches);
각 클래스를 가지는 객체를 불러온다.
change와 keyup 이벤트에 해당하는 이벤트 리스너를 등록한다.
3. 배운 점 & 느낀 점
.json() 메서드 - https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/JSON fetch를 사용할 때 요청을 보낸 후 오는 응답에 대해 .json()을 해줘야한다. |
.match() 메서드 - https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/match 문자열이 정규식과 매치되는 부분을 검색 정규식에 g플래그가 포함될 때, 일치하는 하위 문자열을 포함하는 Array를 반환 |
.join() 메서드 - https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/join 배열의 모든 요소를 연결해 하나의 문자열로 만든다. |
.replace() 메서드 - https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/replace 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환 |
RegExp() - https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/RegExp RegExp 생성자는 패턴을 사용해 텍스트를 판별할 때 사용 |
정규표현식 - https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Regular_Expressions 문자열에 나타나는 특정 문자 조합과 대응시키기 위해 사용되는 패턴 |
읽어주셔서 감사하고 틀린 점이 있다면 꼭 알려주시면 감사하겠습니다!!