As a beginner in JS, I thought I had event handlers figured out. After hours of searching for a solution, I'm stuck. I'm trying to create a carousel, and while it mostly works, when I attempt to pass an event handler and two variables from one function to another, I get a console error: "Uncaught TypeError: e.preventDefault is not a function". If someone could help me understand what I'm doing wrong, I would greatly appreciate it. Here's my code:
const boxList = document.querySelectorAll(".second-section .js-s19-item");
const firstBoxEl = document.querySelector(".second-section .js-s19-item:first-of-type");
const lastBoxEl = document.querySelector(".second-section .js-s19-item:last-of-type");
const boxListArr = [...boxList];
function clickRight(e, activeClassNumber, activeClassNumberConstants) {
e.preventDefault();
boxList.forEach(el => {
el.classList.remove("active");
});
const slicedArr = boxListArr.slice(activeClassNumber, activeClassNumber + activeClassNumber);
slicedArr.forEach(el => el.classList.add("active"));
activeClassNumber = activeClassNumber + activeClassNumber;
if (firstBoxEl.classList.contains('active')) {
jQuery(".left").css("display", "none");
jQuery(".right").css("display", "block");
} else if (lastBoxEl.classList.contains('active')) {
jQuery(".left").css("display", "block");
jQuery(".right").css("display", "none");
} else {
jQuery(".left").css("display", "block");
jQuery(".right").css("display", "block");
}
}
function clickLeft(e, activeClassNumber, activeClassNumberConstants) {
e.preventDefault();
boxList.forEach(el => {
el.classList.remove("active");
});
activeClassNumber = activeClassNumber - activeClassNumberConstants;
const slicedArr = boxListArr.slice(activeClassNumber - activeClassNumberConstants, activeClassNumber);
slicedArr.forEach(el => el.classList.add("active"));
if (firstBoxEl.classList.contains('active')) {
jQuery(".left").css("display", "none");
jQuery(".right").css("display", "block");
} else if (lastBoxEl.classList.contains('active')) {
jQuery(".left").css("display", "block");
jQuery(".right").css("display", "none");
} else {
jQuery(".left").css("display", "block");
jQuery(".right").css("display", "block");
}
}
function handleDesktopChange(e) {
if (e.matches) {
let activeElements = document.querySelectorAll(".second-section .js-s19-item:nth-child(-n+3)");
let activeClass = document.querySelectorAll(".active");
let activeClassNumber = document.querySelectorAll(".active").length;
let activeClassNumberConstants = document.querySelectorAll(".active").length;
document.querySelector(".right").addEventListener("click", clickRight(e, activeClassNumber, activeClassNumberConstants));
document.querySelector(".left").addEventListener("click", clickLeft(e, activeClassNumber, activeClassNumberConstants));
boxList.forEach(el => el.classList.remove("active"));
activeElements.forEach(el => el.classList.add("active"));
}
}
mediaQuery.addListener(handleDesktopChange)
handleDesktopChange(mediaQuery)