Code inside DOMContentLoaded event not working

It’s most likely because the DOMContentLoaded event was already fired at this point. The best practice in general is to check for document.readyState to determine whether or not you need to listen for that event at all. if (document.readyState !== ‘loading’) { console.log(‘document is already ready, just execute code here’); myInitCode(); } else { document.addEventListener(‘DOMContentLoaded’, … Read more

addEventListener vs onclick

Both are correct, but none of them are “best” per se, and there may be a reason the developer chose to use both approaches. Event Listeners (addEventListener and IE’s attachEvent) Earlier versions of Internet Explorer implement JavaScript differently from pretty much every other browser. With versions less than 9, you use the attachEvent[doc] method, like … Read more

Variable in JavaScript callback functions always gets last value in loop? [duplicate]

The problem is that you are ‘closing’ over the same variable. var does not declare a variable1. It simply annotates a ‘stop look-up’ for an identifier within a given execution context. Please see Javascript Closures “FAQ Notes” for all the nice details. The sections on ‘execution context’ and ‘scope chain’ are most interesting. The common … Read more

addEventListener on NodeList [duplicate]

There is no way to do it without looping through every element. You could, of course, write a function to do it for you. function addEventListenerList(list, event, fn) { for (var i = 0, len = list.length; i < len; i++) { list[i].addEventListener(event, fn, false); } } var ar_coins = document.getElementsByClassName(‘coins’); addEventListenerList(ar_coins, ‘dragstart’, handleDragStart); or … Read more

Custom event listener on Android app

Define a callback interface public interface NewsUpdateListener { void onNewsUpdate(<News data to be passed>); } Provide a registration facility on the background thread which gets the RSS feed class <Background processing class name> { …. ArrayList<NewsUpdateListener> listeners = new ArrayList<NewsUpdateListener> (); …. public void setOnNewsUpdateListener (NewsUpdateListener listener) { // Store the listener object this.listeners.add(listener); } … Read more

addEventListener on a querySelectorAll() with classList [duplicate]

There are some dissimilarities between the code and the link you have provided. There is no function doit() in there. You have attached addEvenListener to the NodeList in cbox.addEventListener(“click”,….., you have to loop through the list and attach the event to the current element: Try the following: const cbox = document.querySelectorAll(“.box”); for (let i = … Read more