Review Carousel 

세번째 예제는 Review Carousel을 만드는 것이다. 

이 예제에서는 버튼을 누르면 랜덤으로 리뷰를 보여주는 기능을 만들 수 있다.

 

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Starter</title>
    <!-- font-awesome -->
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css"
    />

    <!-- styles -->
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <main>
      <section class="container">
        <!-- title -->
        <div class="title">
          <h2>our reviews</h2>
          <div class="underline"></div>
        </div>
        <!-- review -->
        <article class="review">
          <div class="img-container">
            <img src="person-1.jpeg" id="person-img" alt="" />
          </div>
          <h4 id="author">sara jones</h4>
          <p id="job">ux designer</p>
          <p id="info">
            Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto
            asperiores debitis incidunt, eius earum ipsam cupiditate libero?
            Iste, doloremque nihil?
          </p>
          <!-- prev next buttons-->
          <div class="button-container">
            <button class="prev-btn">
              <i class="fas fa-chevron-left"></i>
            </button>
            <button class="next-btn">
              <i class="fas fa-chevron-right"></i>
            </button>
          </div>
          <!-- random button -->
          <button class="random-btn">surprise me</button>
        </article>
      </section>
    </main>
    <!-- javascript -->
    <script src="app.js"></script>
  </body>
</html>

 

1. 리뷰 객체 배열 설정 

const reviews = [
  {
    id: 1,
    name: 'susan smith',
    job: 'web developer',
    img: 'https://www.course-api.com/images/people/person-1.jpeg',
    text: "I'm baby meggings twee health goth +1. Bicycle rights tumeric chartreuse before they sold out chambray pop-up. Shaman humblebrag pickled coloring book salvia hoodie, cold-pressed four dollar toast everyday carry",
  },
  {
    id: 2,
    name: 'anna johnson',
    job: 'web designer',
    img: 'https://www.course-api.com/images/people/person-2.jpeg',
    text: 'Helvetica artisan kinfolk thundercats lumbersexual blue bottle. Disrupt glossier gastropub deep v vice franzen hell of brooklyn twee enamel pin fashion axe.photo booth jean shorts artisan narwhal.',
  },
  {
    id: 3,
    name: 'peter jones',
    job: 'intern',
    img: 'https://www.course-api.com/images/people/person-4.jpeg',
    text: 'Sriracha literally flexitarian irony, vape marfa unicorn. Glossier tattooed 8-bit, fixie waistcoat offal activated charcoal slow-carb marfa hell of pabst raclette post-ironic jianbing swag.',
  },
  {
    id: 4,
    name: 'bill anderson',
    job: 'the boss',
    img: 'https://www.course-api.com/images/people/person-3.jpeg',
    text: 'Edison bulb put a bird on it humblebrag, marfa pok pok heirloom fashion axe cray stumptown venmo actually seitan. VHS farm-to-table schlitz, edison bulb pop-up 3 wolf moon tote bag street art shabby chic. ',
  },
];

- 배열을 만들어서 이 안에 작성된 리뷰 데이터를 넣는다. 한 사람의 데이터는 딕셔너리 형태로 설정되어 있고 각각 id, name, job, img, text데이터를 추가할 수 있다. 

 

2. 초기 설정 

let currentItem = 0;

첫번째 리뷰를 초기 항목으로 설정하는 과정이다. 

 

3. DOM요소 선택 

const img = document.getElementById('person-img');
const author = document.getElementById('author');
const job = document.getElementById('job');
const info = document.getElementById('info');

const prevBtn = document.querySelector('.prev-btn');
const nextBtn = document.querySelector('.next-btn');
const randomBtn = document.querySelector('.random-btn');

- 변수에 getElementById와 querySelector를 이용하여 각각의 맞는 id와 class값을 선택한다. 

 

4. 초기 아이템 로드 

window.addEventListener('DOMContentLoaded', function () {
  const item = reviews[currentItem];
  img.src = item.img;
  author.textContent = item.name;
  job.textContent = item.job;
  info.textContent = item.text;
});

- 여기서 등장하는 window객체란 무엇일까? 

1. 브라우저 안의 모든 요소들이 소속된 객체로, 최상위에 있기 때문에 어디서든 접근이 가능하여 '전역객체'라고 불린다. 

2. 일반적으로 우리가 열고 있는 브라우저의 창을 의미하며 이 창을 제어하는 다양한 메서드를 제공한다. 

- 여기서는 이벤트 리스너를 추가하여 웹페이지가 로드된후 실행할 코드를 지정한다. 

 

- addEventListenr에서 "DOMContentLoaded"이벤트는 초기 html문서가 완전히 로드되고 파싱되었을 때 발생한다.

스타일시트, 이미지, 하위 프레임의 로드가 완료될 때까지 기다리지 않고 페이지의 나머지 리소스가 로드되기 전에 필요한 초기화 작업을 수행할 수 있다. 

 

- const item =reveiws[currentItem];

현재 표시할 리뷰 객체를 가져온다.  reviews 배열에서 currentItem인덱스에 있는 객체를 item변수에 저장한다. currentItem은 현재 선택된 리뷰의 인덱스를 나타내며 초기값은 0이다. 

 

- img.src=item.img;

HTML요소 img의 src속성을 현재 리뷰 객체의 img속성으로 설정한다. 이는 이미지 요소가 해당 URL을 사용하여 이미지를 로드하게 한다. 

 

- author.textContent = item.name;

- job.textContent = item.job;

- info.textContent = item.text;

HTML의 author, job, info속성을 리뷰 객체의 각각 name, job, text속성으로 설정한다. 

 

5. 특정 리뷰를 표시하는 함수 

function showPerson(person) {
  const item = reviews[person];
  img.src = item.img;
  author.textContent = item.name;
  job.textContent = item.job;
  info.textContent = item.text;
}

- 주어진 인덱스에 따라 리뷰를 표시하는 함수

 

6. 다음 및 이전 버튼 

nextBtn.addEventListener('click', function () {
  currentItem++;
  if (currentItem > reviews.length - 1) {
    currentItem = 0;
  }
  showPerson(currentItem);
});

prevBtn.addEventListener('click', function () {
  currentItem--;
  if (currentItem < 0) {
    currentItem = reviews.length - 1;
  }
  showPerson(currentItem);
});

- 다음버튼을 클릭하면 currentItem이 1 씩 증가하게 된다.

- 이전버튼을 클릭하면 currentItem이 1씩 감소하게 된다.

- 만약 마지막 리뷰 인덱스를 넘어서게 되면 첫번째 리뷰로 돌아가게 설정되었다. 

 

7. 랜덤버튼

randomBtn.addEventListener('click', function () {
  currentItem = Math.floor(Math.random() * reviews.length);
  showPerson(currentItem);
});

 

- 무작위 버튼에 이벤트 리스너를 추가하여 무작위로 리뷰가 표시될 수 있도록 한다.

 

'개발 > javascript' 카테고리의 다른 글

[JS] 사이드 바 만들기  (1) 2024.06.16
[JS] 반응형 네비게이션바  (0) 2024.06.09
[JS] Counter 만들기  (1) 2024.06.08
[JS]Color Flipper 만들기2  (2) 2024.06.07
[JS] Color Flipper만들기  (0) 2024.06.07

+ Recent posts