한 걸음씩

[JS] Carousel 만들기 본문

JS

[JS] Carousel 만들기

winter17 2023. 7. 6. 18:29

[요구사항] 

4개의 프로필이 있다.

오른쪽 화살표를 클릭하면 오른쪽으로 이동

왼쪽 화살표를 클릭하면 왼쪽으로 이동

버튼을 클릭하면 랜덤으로 프로필이 보이게 구현

// index.html
<body>
  <h1>Our <span>Revi</span>ews</h1>
  <div id="card">
    <div class="profile">
      <img src="https://res.cloudinary.com/diqqf3eq2/image/upload/v1586883334/person-1_rfzshl.jpg" alt="">
      <h4 class="name">Susan Smith</h4>
      <p class="job">WEB DEVELOPER</p>
      <p class="info">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</p>
    </div>
    <!-- 케로셀 아이콘 -->
    <div>
      <span class="material-symbols-outlined left">
        chevron_left
        </span>
      <span class="material-symbols-outlined right">
        chevron_right
        </span>
    </div>
    <button class="random">Surprise Me</button>
  </div>
  <script src="app.js"></script>
</body>

 

// app.js
const left = document.querySelector('.left')
const right = document.querySelector('.right')
const randomBtn = document.querySelector('.random') 
const img = document.querySelector('img')
const author = document.querySelector('.name')
const job = document.querySelector('.job')
const info = document.querySelector('.info')

const imgArr = ['https://res.cloudinary.com/diqqf3eq2/image/upload/v1586883334/person-1_rfzshl.jpg',
'https://res.cloudinary.com/diqqf3eq2/image/upload/v1586883409/person-2_np9x5l.jpg',
'https://res.cloudinary.com/diqqf3eq2/image/upload/v1586883417/person-3_ipa0mj.jpg',
'https://res.cloudinary.com/diqqf3eq2/image/upload/v1586883423/person-4_t9nxjt.jpg'
]
const nameArr = ['Susan Smith', 'Anna Johnson', 'Peter Jones', 'Bill Anderson']
const jobArr = ['WEB DEVELOPER', 'WEB DESIGNER', 'INTERN', 'THE BOSS']
const infoArr = ["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",
"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.",
"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.", 
"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."
]
let currentIndex = 0
function onChangeLeft(){
  currentIndex--
  if(currentIndex < 0){
    // 0보다 작아지면, 길이 - 1해서 배열 마지막 요소로 가도록
    currentIndex = nameArr.length - 1 
  }
  updateProfile()
}
function onChangeRight(){
  currentIndex++
  if (currentIndex === nameArr.length){
    currentIndex = 0
  }
  updateProfile()
}
function onRandomBtn(){
  const number = randomGenerator()
  img.src = imgArr[number]
  author.textContent = nameArr[number]
  job.textContent = jobArr[number]
  info.textContent = infoArr[number]
}
function randomGenerator(){
  return random = Math.floor(Math.random() * nameArr.length)
}
function updateProfile(){
  img.src = imgArr[currentIndex]
  author.textContent = nameArr[currentIndex]
  job.textContent = jobArr[currentIndex]
  info.textContent = infoArr[currentIndex]
}
left.addEventListener('click', onChangeLeft)
right.addEventListener('click', onChangeRight)
randomBtn.addEventListener('click', onRandomBtn)

1. 이미지, 이름, 직업, 정보에 대한 내용을 배열로 각각 생성한다.

 

 ∴ 왼쪽 버튼, 오른쪽 버튼 구현하기 전 currentIndex라는 변수를 생성해야 한다. 인덱스로 접근할 계획!

2023.07.06 - [JS] - [JS] Number Counter → 참고해 보기

2. 왼쪽 버튼 onChangeLeft() 함수

왼쪽 버튼은 인덱스를 내림차순으로 순회해야 하기 때문에 (3-2-1-0)

currentIndex-- 해야 하는데

인덱스가 음수값이 나오는 경우가 있어서 조건을 설정해줘야 한다.

currentIndex가 음수일 경우 배열의 마지막 인덱스를 가리키도록!

 

3. 오른쪽 버튼 onChangeRight() 함수

오른쪽 버튼은 인덱스를 오름차순으로 순회해야 하기 때문에 (0-1-2-3)

currentIndex++ 해야 하는데

인덱스가 배열을 벗어나는 경우가 있어서 조건을 설정해줘야 한다.

currentIndex가 배열을 벗어날 경우 인덱스를 0으로 초기화!

 ∴  updateProfile() 함수는 left, right 버튼에서 같은 내용을 가지기 때문에 중복 코드를 방지하기 위해서 코드의 가독성과 유지보수성을 향상할 수 있도록 하였다. 

 

4. 랜덤 버튼 onRandomBtn() 함수

2023.07.06 - [JS] - [JS] Random Color 2 → 참고해 보기

랜덤 버튼 같은 경우는 이전에 경험해 봤던 랜덤 배경 컬러와 같은 논리이다.

randomGenerator() 함수에서 랜덤 번호를 생성 후

onRandomBtn() 함수에서 number라는 변수를 생성하는데 randomGenerator() 함수를 담을 용도이다.

바꿔야 하는 태그의 요소마다 함수를 호출하면 각각의 정보들이(img, author, job, info) 전부 따로 나오기 때문에 변수에 담아서 randomGenerator() 함수를 한 번만 호출할 수 있도록 해야 한다. 

'JS' 카테고리의 다른 글

[JS] FAQ(자주 묻는 질문) 페이지 만들기 ✅  (0) 2023.07.10
[JS] 반응형 Navbar, Sidebar 만들기  (0) 2023.07.07
[JS] Number Counter 만들기  (0) 2023.07.06
[JS] Random Color 2 - color flipper 만들기  (0) 2023.07.06
[JS] To Do List  (0) 2023.07.03