'how do i use a changeable value in a function parameter?

it's pretty hard to explain, but I know why what I tried doesn't work I just want to know if there is a solution. I hope you can understand what I want to do through the code

async function copyInvite() {
    let buttons = document.querySelectorAll("button.rl-btn-invite");

    addEventListenerLoop(buttons, 'click', event => { navigator.clipboard.writeText(node.id); });
}



async function addEventListenerLoop(nodes, type, code) {
    for (const node of nodes) {
        node.addEventListener(type, code);
    }
}

I am trying to make a value in the function change based on what node I am doing it on

I tried using mutable values but it either didn't work or I didn't try well enough.



Solution 1:[1]

Given your example, the simplest solution would be to use event.currentTarget instead of node to refer to the element the handler was bound to:

addEventListenerLoop(
  buttons,
  'click',
  event => { navigator.clipboard.writeText(event.currentTarget.id); }
  //                                       ^^^^^^^^^^^^^^^^^^^
);

Solution 2:[2]

If I understand you right, you are looking for a solution to have access to the current node in your code callback.

For this, you can try to nest your callback methods, where the outer one receives the current node and returns the actual event handler for this specific node.

This will look like this:

async function copyInvite() {
    let buttons = document.querySelectorAll("button.rl-btn-invite");

    addEventListenerLoop(buttons, 'click', node => event => { navigator.clipboard.writeText(node.id); });
}


async function addEventListenerLoop(nodes, type, code) {
    for (const node of nodes) {
        node.addEventListener(type, code(node));
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Felix Kling
Solution 2 Janik