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.)
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.
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).
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.
JavaScript Document own method: addEventListener() It does not return any value.
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);
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 ");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With