Home > Enterprise >  how to have multiple addEventListener in one function
how to have multiple addEventListener in one function

Time:09-15

I have a button and an input. The function works on the input, but I don't know how I can make it so that the function checks for a keydown and a mouse-up event.

function myFunction(){
        console.log('test');
        // // Get the input field
        var el = document.getElementById("myInput");
        el.addEventListener("keydown", function(event) {
        if (event.key === "Enter") {
            var input = document.getElementById("myInput").value;
            console.log(input)
            localStorage.setItem("storageName",input);
            console.log('Sending data');
            document.location = 'search.php';
        }
        })
<div >
   <button id="glas" onclick="myFunction()"for="search"><i  aria-hidden="true"></i></button>
   <input  type="text" id="myInput" onkeyup="myFunction()" placeholder="Zoek workshops.." title="Type in a name">
</div>

CodePudding user response:

The current logic you have is wrong: in HTML you have attached myFunction as keyup handler to the input element, but then inside myFunction, you attach yet again an event handler to the input element. This practically means that every time the user releases a key in the input control, a new event handler is accumulated to that input element. This is going to accumulate...

Instead, remove the onclick and keypress attributes from your HTML and use addEventListener only.

Some other issues:

  • Storing something in localStorage is not going to get the string to the PHP server.
  • The for attribute has no meaning for a button element.

Then to your core question: just isolate the common part from what both events should do. As the check for the Enter-key is only for the event on the input element -- and not for the button event -- that part should not be in the common function.

Here is how it could look:

const inputElem = document.getElementById("myInput");
const buttonElem = document.getElementById("glas");

inputElem.addEventListener("keypress", (e) => {
    if (e.key === "Enter") process();
});

buttonElem.addEventListener("click", process);

function process() { // Function with the common logic
    // Common code:
    console.log('test', inputElem.value);
    // Other logic...
}
<div >
    <button id="glas">Search</button>
    <input  type="text" id="myInput" placeholder="Zoek workshops.." title="Type in a name">
</div>

  • Related