-1

I want to reause one long function in multiple event listeners.

Is there a way I can reuse javascript functions in multiple event listeners (without jQuery or other libraries).

I've tried a few things.

function one(){
    console.log("not supposed to show until I press the variable containing num1")
};


num1.addEventListener('click', one());

Runs the function at the beginning and doesn't run on click

num1.addEventListener('click', function one(){
    console.log("oops")
});
num2.addEventListener('click', one());

Runs when I press num1 doesn't work when I pess num2

const one = () => {console.log("Still not working")}
num1.addEventListener('click', one());

same issue as with the first example.

I want to reause one long function in multiple event listeners.

MoreeZ
  • 118
  • 6
  • 2
    Possible duplicate of [addEventListener calls the function without me even asking it to](https://stackoverflow.com/questions/16310423/addeventlistener-calls-the-function-without-me-even-asking-it-to) – Ivar Feb 22 '19 at 19:38

3 Answers3

1

You should use like this num1.addEventListener("click", one); num2.addEventListener("click", one); With function one(...){...} previously declared

Luis Barajas
  • 478
  • 3
  • 12
0

you should provide a function to be called by the event listener, but by doing doing one() you are not providing function instead providing whatever is returning by that function.

like @Luis Barajas mentioned, do num1.addEventListener("click", one)

SanthoshN
  • 619
  • 3
  • 15
0

one() return undefined you are passing undefined instead of callback.You can pass a function and call one() inside it.

let num1 = document.querySelector('#num1');
let num2 = document.querySelector('#num2');


function one(){
  console.log("Its working ");
}
num1.addEventListener('click', (e) => {
  one()
});
num2.addEventListener('click', (e) => {
  one()
});
<button id="num1">Num 1</button>
<button id="num2">Num 2</button>
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73