Home > Blockchain >  How to properly call a function in different type addEventListeners
How to properly call a function in different type addEventListeners

Time:03-27

I have this code where I use el and e variables to do various things. Heres the barebones version

const typeButton = document.querySelectorAll('button');

typeButton.forEach((el) => {
  el.addEventListener('click', (e) => {
    let btnTarget = e.target;
    console.log(btnTarget);
    console.log(el);
  });
});

It works all good, but I have to make it also trigger when tab focus is used. So my idea was to put the contents in a function and call it with two different addEventListeners, one click and second if keydown is tab.

function btnActivate() {
  console.log('end23');
  let btnTarget = e.target;
  console.log(btnTarget);
}

typeButton.forEach((el) => {
  el.addEventListener('click', function(e) {
    console.log('clicked');
    btnActivate();
  });
});

Unfortunately, this does not work and variables e and el will stay undefined. What can I do to make it work?

const typeButton = document.querySelectorAll('button');
/*
typeButton.forEach((el) => {
  el.addEventListener('click', (e) => {
    let btnTarget = e.target;
    console.log(btnTarget);
    console.log(el);
  });
});
*/

////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////

console.log('test12345678');

function btnActivate(e) {
  //typeButton.forEach((el) => {
  //el.addEventListener('click', (e) => {
  console.log('end23');
  let btnTarget = e.target;
  console.log(btnTarget);
  //});
  //});
}

typeButton.forEach((el) => {
  el.addEventListener('click', function(e) {
    console.log('clicked');
    btnActivate(e);
  });
});
/*
typeButton.forEach((el) => {
  el.addEventListener('click', function(e) {
    console.log('clicked');
    btnActivate();
  });
});
*/

//document.addEventListener('focus', btnActivate());


/*
window.addEventListener('keydown', function (e) {
  const code = e.keyCode || e.which;

  if (code == 9) {
    console.log('test1');
    btnActivate();
  }
  
});
*/
body {
  background: #333;
  padding: 50px;
  margin: 0;
}
<button >Button 1</button>
<button >Button 2</button>
<button >Button 3</button>

CodePudding user response:

You need to pass the e (Event) to your btnActivate function.

Btw how about:

typeButton.forEach((el) => {
  el.addEventListener('click', function(e) {
    console.log('clicked');
  });
  el.addEventListener('keydown', function(e) {
    if (e.keyCode === ) {
       console.log('pressed tab');
    }
  });
});

CodePudding user response:

Easiest way is to pass e as an argument to your function:

function btnActivate(e) {
  console.log('end23');
  let btnTarget = e.target;
  console.log(btnTarget);
}

typeButton.forEach((el) => {
  el.addEventListener('click', function(e) {
    console.log('clicked');
    btnActivate(e);
  });
});

You can do similar with el if you need to, as well.

  • Related