Error encountered: When trying to pass an event and two variables, the function e.preventDefault is not recognized as a valid

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) 

Answer №1

Make sure to use the following code instead:

document.querySelector(".right").addEventListener("click", e => clickRight(e, activeClassNumber, activeClassNumberConstans));

The issue lies in not passing the event as an argument to the clickRight function, resulting in it being undefined.

Essentially, your current approach executes the function and expects its return to act as the event handler.


Diving Deeper into this Concept

In the code example provided:

const keyChangesSlide = (e) => { 
  if(e.keyCode === 37) { 
    changesSlideLeft(); 
  }
};

window.addEventListener("keydown", keyChangeSlide)

This works effectively as it is translated to:

window.addEventListener("keydown", (e) => {
  if(e.keyCode === 37) { 
    changesSlideLeft(); 
  }
})

The crucial points here are that it operates as a callback function and accepts e as a parameter within the callback.

On the other hand, your implementation based on the given example would have appeared like this:

window.addEventListener("keydown", keyChangeSlide(e))

Which would have resulted in:

window.addEventListener("keydown", undefined)

Why is that?

This is because you need to provide a function as the second parameter for the addEventListener function. By calling a function with a parameter, you end up passing the return value of the function, which is ultimately undefined in this case due to no explicit return statement.

The error occurred because the argument e was passed as undefined in that context.

Answer №2

modify:

document.querySelector(".right").addEventListener("click", clickRight(e, activeClassNumber, activeClassNumberConstans));
document.querySelector(".left").addEventListener("click", clickLeft(e, activeClassNumber, activeClassNumberConstans));

as follows:

document.querySelector(".right").addEventListener("click", e => clickRight(e, activeClassNumber, activeClassNumberConstans));
document.querySelector(".left").addEventListener("click", e => clickLeft(e, activeClassNumber, activeClassNumberConstans));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for sending data from a JSP to a Servlet with Javascript

My code creates an array of circular buttons with dynamic values. When clicked, these buttons get deleted and their values are stored in a JavaScript object array. I need to send these deleted button values to a servlet once my task is complete. To do this ...

Undefined value is encountered when passing props through the Context API in a REACT application

Exploring My Context API Provider File (Exp file) import react form 'react'; import {createContext} from "react"; export const ContextforFile = createContext(); export function ContextData(props){ let rdata=props.data return( &l ...

Is it possible to import a component from a production build of create-react-app?

Has anyone tried importing a component from a production build of create-react-app? Situation: I have one CRA project that has been built for production. Inside this project, there is a component named ExampleButton. Now, I am working on a second CRA pro ...

"Transferring a JavaScript variable to Twig: A step-by-step guide for this specific scenario

When it comes to loading a CSS file based on the user's selected theme, I encountered an issue while trying to implement this in my Symfony application using Twig templates. The code worked flawlessly on a simple HTML page, but transferring it to a Tw ...

Achieve a new line break when the user hits the "Enter" key using HTML and JavaScript

I'm in the process of developing a Chrome Extension that allows users to create a to-do list. My goal is to enable users to submit their task by pressing the "Enter" key, which should move the task to the next line after submission. I am currently fac ...

The behavior of CSS position: sticky varies depending on whether the user is scrolling up or scrolling down

I am experiencing an issue in my Vue CLI app where a component with the position: sticky CSS property is being partially hidden under the top of the browser when scrolling down, but works correctly when scrolling up. This behavior is also observed on my Ga ...

Unable to use the .focus() method on a Link component by utilizing references in React Router 4

I am currently working with the Link component in react-router (v4). I have successfully attached a ref to this component and can log the reference. However, when I try to use linkRef.current.focus(), I encounter the following error: linkRef.current.focu ...

Having trouble rendering a dynamic table with JavaScript utilizing a JSON object

I am struggling to retrieve data in JSON format and display it in a table. Despite trying various methods, I have been unable to make it work. Below is the code for this function. Can someone please assist me in identifying what is wrong with it? As of now ...

Creating a primary php file in Apache without the use of SQL or any database: is it possible?

Forgive me if this comes across as rude, but I'm struggling to grasp the concept of apache, PHP, and servers in general. To help myself understand better, I want to create a very basic website that assigns an ephemeral ID to each user (not a session). ...

Adjusting the overflow of a parent div based on the position of the div within it by scrolling

I'm trying to create a page with 3 different sections: <div class="container" id="main-container"> <div class="section" id="profile"> Hello World </div> <div class="section" id="projects"> Hello World 2 ...

What is the ideal destination for my Ajax request to be sent?

When utilizing jQuery, in the event of sending an Ajax request you must provide the URL to direct towards. For instance: $.get("someurl", function(data) { console.log(data); }); The query at hand is: should the URL indicate a page on the server, trea ...

Floating Action Button combined with a Material UI ListItem

I am working on creating a basic list with a listItem that includes a button. The code I currently have is as follows: import React from "react"; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; import MuiThemeProvider ...

Preserve multiple selected values post form submission using PHP, HTML, and JavaScript

How can I retain the selected values in a form after it is submitted? My current code functions correctly when only one value is selected, but does not maintain all selected values when multiple are chosen simultaneously. Any assistance would be apprecia ...

What is the best way to invoke a function in one View Model from within another View Model?

I am looking to divide my DevExtreme Scheduler into two separate view models. One will be responsible for displaying the Scheduler itself, while the other will handle the Popup and button functionality. Despite having everything set up, I am struggling to ...

Concealing the source code within a Next.js application

Currently, I am utilizing next.js for a project. We have a contact page where we display email addresses in cards, but we want to prevent bots from accessing this information. A solution was discovered by one of my colleagues to hide the email addresses i ...

Is there a way to consistently substitute a specific path parameter with a different value within node.js?

Snippet of my coding: router.get('/name/:name/height', (req,res) => { ... } router.get('/name/:name/weight', (req,res) => { ... } router.get('/age/:age/height', (req,res) => { ... } router.get('/ag ...

Tips for including MUI icon within a list displayed on a map:

Initially, I brought in the AccountCircle Icon from MUI: import { AccountCircle } from '@mui/icons-material'; Then, I utilized styled to customize the icon: const UserIcon = styled(AccountCircle)({ margin: '0px 0px 0px 0px', }); My ex ...

tips for incorporating async/await within a promise

I am looking to incorporate async/await within the promise.allSettled function in order to convert currency by fetching data from an API or database where the currency rates are stored. Specifically, I want to use await as shown here, but I am unsure abou ...

Ensure data accuracy by triggering the cache - implementing SWR hook in Next.js with TypeScript

I recently implemented the swr hook in my next.js app to take advantage of its caching and real-time updates, which has been incredibly beneficial for my project (a Facebook clone). However, I encountered a challenge. The issue arises when fetching public ...

What sets apart `var now = new Date();` and `var now = Date();` in JavaScript

I am specifically interested in exploring the impact of adding "new" on the variable, as well as understanding when and why it is used. I would also like to understand why I am obtaining identical answers when printing both versions. ...