Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
how can i pass a dynamic argument to a EventListener?

have this code:

   function roleDescription() {
    // вторая ступень = описание роли при наведении, выбор роли при клике
    for (let i = 0; i < originDescription.length; i++) {
      buttons[i].addEventListener('mouseover', asignDesc);
      buttons[i].addEventListener('click', asignRole, {
        once: true
      });
    }
  }

and this functions:

    function asignRole(i) {
    playerrole = role[i];
    alert(playerrole);
    makeSpecial();
  }

  function asignDesc(i) {
    maintext.textContent = originDescription[i];
    maintext.style.fontSize = '15px';
  }

how can i pass [i] from cycle [for] so i can get all this scipt goin' well?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

You can use bind

const buttons = document.querySelectorAll("button");
const originDescription = buttons;

for (let i = 0; i < originDescription.length; i++) {
  buttons[i].addEventListener('click', asignRole.bind(buttons[i], i), {
    once: true
  });
}


function asignRole(i) {
  console.log(i);
}
<button type="button">0</button>
<button type="button">1</button>
<button type="button">2</button>

You can use a function

const buttons = document.querySelectorAll("button");
const originDescription = buttons;

for (let i = 0; i < originDescription.length; i++) {
  buttons[i].addEventListener('click', () => asignRole(i), {
    once: true
  });
}


function asignRole(i) {
  console.log(i);
}
<button type="button">0</button>
<button type="button">1</button>
<button type="button">2</button>

You can use data attributes

const buttons = document.querySelectorAll("button");
const originDescription = buttons;

for (let i = 0; i < originDescription.length; i++) {
  buttons[i].addEventListener('click', asignRole, {
    once: true
  });
}


function asignRole(evt) {
  console.log(evt.currentTarget.dataset.id);
}
<button type="button" data-id="0">0</button>
<button type="button" data-id="1">1</button>
<button type="button" data-id="2">2</button>

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!