Skip to content Skip to sidebar Skip to footer

Addeventlistener After Appendchild

I create an element, eltTooltip, with document.createElement etc and add it to the DOM like this (idTooltip contains the id of eltTooltip): document.body.appendChild(eltTooltip); v

Solution 1:

Your way works perfectly fine but it's probably better to attach the event listener before you add it to the DOM using eltTooltip. This saves you from fetching the element from the DOM.

Demo

var idTooltip = 'test';
var eltTooltip = document.createElement('div');
eltTooltip.innerHTML = "test"
eltTooltip.setAttribute('id', idTooltip);
eltTooltip.addEventListener("click", function () {
    alert('click');
});

document.body.appendChild(eltTooltip);

Solution 2:

You could do something like this

window.onload = function (){
    var toolTip = document.createElement('div');
    toolTip.innerHTML = "someData";
    toolTip.addEventListener('click', myfunction);
    document.body.appendChild(toolTip);

    functionmyfunction(){
        alert("hello guys ");
    }
}

Post a Comment for "Addeventlistener After Appendchild"