Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener after appendChild

Tags:

javascript

dom

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);
var addedElt = document.getElementById(idTooltip);
addedElt.addEventListener("click", function(){...});

Is the click event guaranteed to be added here, or is perhaps the DOM not ready for that?

Could I do this in a better way? (The page is loaded long ago so window.onload can not be used. And I can't use jQuery here.)

like image 619
Leo Avatar asked Jan 22 '14 19:01

Leo


People also ask

Is it better to use onclick or addEventListener?

Both can be used to handle events. However, addEventListener should be the preferred choice since it can do everything onclick does and more. Don't use inline onclick as HTML attributes as this mixes up the javascript and the HTML which is a bad practice. It makes the code less maintainable.

Why is addEventListener not working?

The "addEventListener is not a function" error occurs for multiple reasons: calling the method on an object that is not a valid DOM element. placing the JS script tag above the code that declares the DOM elements. misspelling the addEventListener method (it's case sensitive).

Can you use addEventListener with querySelectorAll?

To add an event listener to the results from the querySelectorAll method: Use the forEach() method to iterate over the collection of elements. Call the addEventListener() method on each element in the collection.

What does addEventListener return?

JavaScript Document own method: addEventListener() It does not return any value.


2 Answers

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);
like image 59
Daniel Imms Avatar answered Oct 17 '22 02:10

Daniel Imms


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);

    function myfunction(){
        alert("hello guys ");
    }
}
like image 39
Suman Bogati Avatar answered Oct 17 '22 02:10

Suman Bogati