javascripthtmlwebecmascript-6frontend

Handle Event and define parameter after event parameter in javascript


let testTime = document.querySelectorAll(".testTime"); // this List has 3 value. 30, 60, 120
testTime.forEach((x) => {
    console.log(x.innerHTML);
    addEventListener("click", selectTime(this, x));
});

function selectTime(e, item) {
    e.preventDefault();
    
}

I want to define a parameter, after e parameter and e.preventDefault() for the function selectTime.

And I want to use item in selectTime

testTime.forEach((x) => {
    console.log(x.innerHTML);
    addEventListener("click", selectTime(this, x));
});

I use this keyword but It gave me an error

Uncaught TypeError: e.preventDefault is not a function
    at selectTime (time.js:20:7)
    at time.js:13:31
    at NodeList.forEach (<anonymous>)
    at time.js:11:10

Solution

  • Your logic and syntax is all wrong. You don't callthe event listener to anything in your forEach loop and you are calling selectTime the wrong way in the addEventListener function. addEventListener must be always called on some DOM element, and as the second argument you pass it a callback function which will be called after the click is fired. When you pass a callback function, you just pass the function definition, without parentheses. What you're doing now is calling the function. This is how the code should be properly structured

    let testTime = document.querySelectorAll(".testTime");
    testTime.forEach((time) => {
        console.log(time.innerHTML);
        time.addEventListener("click", (event) => {
            selectTime(event, time)
        });
    });
    
    function selectTime(e, item) {
        e.preventDefault();
        
    }