Vanilla JS PJ (Our Logs)

송민혁·2022년 8월 17일
0
post-thumbnail

Intro

  • Box
  • Image
  • Text
  • Arrow Button
  • Like Button

JS

// local reviews data
const reviews = [
  {
    id: 1,
    name: "Leo Hong",
    job: "CS Engineer",
    img:
      "./Images/홍석원.png",
    text:
      "Perpetual optimism is a force multiplier.",
  },
  {
    id: 2,
    name: "Lee",
    job: "Registered Nurse",
    img:
      "./Images/이철한.png",
    text:
      "Love is, above all else, the gift of oneself.",
  },
  {
    id: 3,
    name: "Matthew Song",
    job: "FrontEnd Engineer",
    img:
      "./Images/송민혁.png",
    text:
      "The gratification comes in the doing, not in the results.",
  },
];

// select items
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");

// set starting item
let currentItem = 0;

// load initial item
window.addEventListener('DOMContentLoaded', function() {
  showPerson(currentItem);
})

// show person based on item

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

// show next person

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

prevBtn.addEventListener("click", function () {
  currentItem--;
  if(currentItem < 0) {
    currentItem = 2;
  }
  showPerson(currentItem);
});

여기서 핵심은 화살표버튼을 눌렀을 때, 다른 정보가 나오는 것이다. 우선적으로 정보들이 있는 배열과 객체를 만든다.

그리고 html에 있는 요소들을 다 연결해준다.

로딩 이벤트, 화살표 버튼 이벤트와 함수를 된다.

배운 점

  • DOMContentLoaded: 창을 불러올 때 사용하는 이벤트이다.
  • 화살표 버튼을 누르다가 배열의 길이보다 큰 숫자를 대응하는 법을 배웠다.
    조건문으로 초기설정으로 돌아가거나 마지막 인덱스로 가면 끝이었다.

0개의 댓글