Muscardinus

Instant Search 본문

FrontEnd/Basic Skills

Instant Search

Muscardinus 2022. 3. 21. 00:22
728x90
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./styles.css" />
    <title>Instant Search</title>
  </head>
  <body>
    <div class="SearchContainer">
      <input type="text" class="SearchInput" />
      <span class="LoadingIndicator">Loading...</span>
    </div>
    <div>
      <ul class="TextList"></ul>
      <p class="InfoParagraph"></p>
    </div>
    <script type="module" src="./app.js"></script>
  </body>
</html>
const API_URL = 'https://api.thecatapi.com/v1/breeds/search';

const $searchInput = document.querySelector('.SearchInput');
const $loadingIndicator = document.querySelector('.LoadingIndicator');
const $textList = document.querySelector('.TextList');
const $infoParagraph = document.querySelector('.InfoParagraph');

// Write code here.
$searchInput.addEventListener("keyup", async (e) => {
    const query = e.target.value;

    if (!query) return;

    $loadingIndicator.style.visibility = "visible";
    const response = await fetch(`${API_URL}?q=${query}`);
    const cats = await response.json();
    $loadingIndicator.style.visibility = "hidden";

    if (!cats.length) {
        $textList.innerHTML = "";
        $textList.style.visibility = "hidden";
        $infoParagraph.innerHTML = "해당하는 검색어가 없습니다..!";
        return;
    }

    $textList.innerHTML = cats.slice(0, 5).map((cat) => `
        <li>${cat.name}</li>
    `).join("");
    $textList.style.visibility = "visible";
    $infoParagraph.innerHTML = "";
});
728x90

'FrontEnd > Basic Skills' 카테고리의 다른 글

React Router 간단 구현  (0) 2022.07.03
Checkbox  (0) 2022.03.21
Tabs  (0) 2022.03.21
Carousel  (0) 2022.03.20
Toggle Button  (0) 2022.03.20
Comments