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

Prioritizing the execution order of useEffect in Next.js

Here is the code snippet from my _app.tsx useEffect(() => { console.log(1) }, []); And this portion of code is from my index.tsx useEffect(() => { console.log(2) }, []); Currently, in the console it prints 21 However, I want it to print 12 ...

Declaring a variable outside of a function or object

It's been a challenge for me to assign a value to the variable result as it always stays undefined. if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } ...

Upgrading the entire document's content using jQuery

I am dealing with an ajax response that provides the complete HTML structure of a webpage, as shown below: <!DOCTYPE> <html> <head> <!-- head content --> </head> <body> <!-- body content --> </b ...

Unit test: Passing a deeply nested object as a prop to a React component

My functional component looks like this: const ImageScreen = (props: any) => { const images: object[] = []; props.navigation.state.params.images.forEach((image: any) => //some code ); return ( <View style={CommonStyles.normalPage} ...

Unclear value of button when being passed

In my Welcome.html file, I am attempting to send the value of a button to a function that simply logs that value. This function is located in a functions class that has been imported into my welcome.ts file. <ion-content padding id="page1"> <h1 ...

Utilize the "incorporate" feature to include any string within an array

I am currently working on improving the search function in my application. This particular search function takes input from a search bar and is designed to handle multiple search terms. For example, it should be able to handle queries like "javascript reac ...

Preserve the values of checkboxes throughout the entire website by utilizing localStorage

Example A functionality in the example allows users to add images to a container by clicking on checkboxes. However, there is an issue where when a checkbox is checked on one page to store an image, and then another checkbox is checked on a different page ...

Bring in styles from the API within Angular

My goal is to retrieve styles from an API and dynamically render components based on those styles. import { Component } from '@angular/core'; import { StyleService } from "./style.service"; import { Style } from "./models/style"; @Component({ ...

Node.js is throwing an error code 344, indicating that it is not possible to manipulate headers after they have already been

I'm still learning about Node and I've encountered this confusing error that I can't seem to figure out. I've searched for similar cases online, but none of them quite match mine. Any help would be greatly appreciated. From what I gathe ...

What are the steps to crafting a basic JavaScript or jQuery function within CodeIgniter?

I'm currently working on creating a basic JavaScript function within CodeIgniter that is triggered when a radio button is clicked. <input type="radio" name="amount" value="<?php echo $plan['amount']; ?>" onclick="fn()" /> The J ...

Extend JavaScript capabilities for window.print() function to automatically include backgrounds

I am looking to add a special magical property to my Print this Page button. This property will automatically enable the default unset option (shown in the picture) which is to print the backgrounds of div colors and background images. <a href="#" oncl ...

"Utilize Vuejs to establish a binding between two objects when necessary

With the help of moment, my calendar generates 41 days. for (let x = 0; x < 42; x++) { context.add(1, 'd'); let day = { 'date': moment(context), 'events': [] }; } ...

An unexpected 'undefined' occasionally tacked onto 1% of the URLs visitors requested on my website starting from June 12, 2012

Ever since June 12, 2012 at 11:20 TU, I have been noticing strange errors in my varnish/apache logs. At times, after a user has requested a page, I observe a similar request moments later but with the URL string after the last "/" being replaced by "undef ...

Endless cycle of React hooks

I am struggling to understand why I keep encountering an infinite loop in my useClick function. I can see that I am updating the state value inside the useEffect using setVal, but according to the second parameter, useEffect should only run on onClick as ...

Attempting to grasp the fundamentals of angular Routing, however, upon attempting to reload the page, nothing appears to be displayed

While working in the Bracket editor, I created a file structure with various files located under the 'scripts' tags within the Index.html file. The root folder is named 'projectAngular', inside which there are subfolders like 'appC ...

Can you determine if the user is holding the CTRL key in a universally recognized way?

Can JQuery or Javascript detect if the user is holding the CTRL key outside of keyPress, keyUp events? Appreciate any insights. Thanks! ...

Ways to verify AJAX Response String when data format is specified as JSON

When using AJAX to retrieve JSON data from a webpage, it's essential to set the responseType to json. If the data processing is successful, a valid JSON string is returned, which works perfectly. However, if there's an error on the webpage, inst ...

Issue encountered when setting a background image in Angular

When trying to add a background image and set it to cover the entire browser window, I encountered an issue where the image appeared very small and did not fully cover the background. As someone new to Angular, my understanding of how this process works i ...

Highcharts JS encountered an error: x[(intermediate value)(intermediate value)(intermediate value)] is not a valid constructor

I'm in the process of creating a bar chart by fetching options from an ajax response. However, I encountered an error when passing the object to the highcharts constructor. Uncaught TypeError: x[(intermediate value)(intermediate value)(intermediate v ...

How can I transfer data from two queries to Jade using Node.js (Express.js)?

I have a database with two tables - one for storing user information and another for managing friendship connections: setting up a friend list in mysql My goal is to create a profile page using Jade, specifically profile.jade: - each user in users ...