본문으로 건너뛰기

Implementing Carousel Functionality

Let's implement carousel functionality using JavaScript.


popularButtons Function Explanation

This function handles the actions of two buttons (popular-left-button and popular-right-button) for scrolling the popular items list left and right.

Variable Setup:

  • items: This code selects all elements with the .popular-item class in the entire document and returns a NodeList.
const items = document.querySelectorAll('.popular-item');
  • leftButton and rightButton: These obtain references to the left and right scroll buttons, respectively.
const leftButton = document.querySelector('.popular-left-button');
const rightButton = document.querySelector('.popular-right-button');
  • currentIndex: A variable used to track the index of the currently visible item. The initial value is set to 0, which represents the first item.
let currentIndex = 0;

Left Button Event Listener

  • Add a 'click' event listener to leftButton, defining the callback function to be executed on click.
  • Within the callback function, if the current index is greater than 0 (meaning it's not the first item), decrease currentIndex and scroll to that item.
leftButton.addEventListener('click', function () {
if (currentIndex > 0) {
currentIndex--;
// ...
}
});

Right Button Event Listener

  • Add a 'click' event listener to rightButton as well.
  • In this case, increase currentIndex and scroll to that item if currentIndex is less than the index of the last item.
rightButton.addEventListener('click', function () {
if (currentIndex < items.length - 1) {
currentIndex++;
// ...
}
});

scrollIntoView Method

  • scrollIntoView is a method that automatically scrolls an element into view. In this case, it is applied to the item corresponding to the current index (items[currentIndex]).
items[currentIndex].scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'start',
});
  • behavior: 'smooth': This option ensures the scrolling happens smoothly, like an animation.

  • block: 'nearest': This option positions the target element as close as possible to the visible area within the scrollable element.

  • inline: 'start': This option places the target element at the start of the scrollable element.

The scrollIntoView method is one of the simple ways to enhance the usability of a web page. It allows users to conveniently view the desired item with just a click of a button, making the site easier to navigate.

다음 내용이 궁금하다면?

월 12,500원 PLUS 멤버십 가입 or 강의를 등록해 주세요!