Implementing Carousel Functionality
Let's implement the carousel functionality using JavaScript.
Explanation of the popularButtons Function
This function handles the behavior of two buttons (popular-left-button
and popular-right-button
) used to scroll through a list of popular items horizontally.
Variable Setup:
items
: This code selects all elements with the.popular-item
class throughout the document and returns a NodeList.
const items = document.querySelectorAll('.popular-item');
leftButton
andrightButton
: These lines grab references to the left and right scroll buttons, respectively.
const leftButton = document.querySelector('.popular-left-button');
const rightButton = document.querySelector('.popular-right-button');
currentIndex
: This variable is used to keep track of the index of the currently visible item on the screen. It is initially set to 0, indicating the first item.
let currentIndex = 0;
Left Button Event Listener
- Add a 'click' event listener to
leftButton
and define a callback function to be executed upon clicking. - Inside the callback function, decrease
currentIndex
(if it's greater than 0), and scroll to the corresponding item.
leftButton.addEventListener('click', function () {
if (currentIndex > 0) {
currentIndex--;
items[currentIndex].scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'start',
});
}
});
Right Button Event Listener
- Add a 'click' event listener to
rightButton
. - Here, we increase
currentIndex
(if it's less than the index of the last item) and scroll to the corresponding item.
rightButton.addEventListener('click', function () {
if (currentIndex < items.length - 1) {
currentIndex++;
items[currentIndex].scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'start',
});
}
});
scrollIntoView Method
scrollIntoView
is a method that scrolls the element into the visible area of the browser, making it smoothly appear in view. It is applied to the item at the current index (items[currentIndex]
).
items[currentIndex].scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'start',
});
behavior: 'smooth'
: This option makes the scrolling smooth and animated.block: 'nearest'
: This option ensures the target element is placed closest to the visible portion of the scrollable element.inline: 'start'
: This option places the target element at the start of the scrollable element.
By following these steps, you can effectively create a scrollable carousel using the scrollIntoView
method and JavaScript event listeners for button clicks.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.