Search code examples
javascriptclone

Changing onclick() breaks cloning process


I'm trying to create a button that clones an element 3 times, but when I try to change the clones onclick(), it doesn't clone the object.

var html = document.getElementById("kaart" + kaart_id).innerHTML;
kaart_id = kaart_id + 1;
var clone = document.createElement("div");
clone.innerHTML = html;
clone.id = "kaart" + kaart_id; 
clone.classList = "memory_kaart";
clone.onclick = kaart(kaart_id);
let tekst = clone.childNodes[1];
tekst.textContent = kaart_waarde;
tekst.id = "kaart" + kaart_id + "_tekst";
document.getElementById("memory_speelveld").appendChild(clone);
kaart_waarde = kaart_waarde + 1;

I'm trying to change the onclick to kaart(kaart_id) which is my other function


Solution

  • You're calling the function kaart(kaart_id) in your assignment which is why the event handler doesn't trigger. You need to pass a reference to the function instead, not call it.

    Assign a reference to the function to the onclick handler by assigning the function declaration:

    clone.onclick = function kaart(kaart_id) {
        // function statements
    }; 
    

    or by assign the function declaration to a variable first, then assigning the variable to the event handler:

    let kaartFunc = function kaart(kaart_id) {
        // function statements
    } 
    
    clone.onclick = kaartFunc; 
    

    A rule of thumb is; if the function does not have the function keyword before its name and it has parentheses () after its name, you are calling the function, e.g kaart(kaart_id).