Skip to content Skip to sidebar Skip to footer

Why Is Addeventlistener Load Preventing Code From Working?

Update: I originally had document.addEventListener('DOMContentLoaded'... and was linking to the JS file in the head of the HTML document. The result was: some parts of another

Solution 1:

3 possible ways to resolve this issue using native javascript:

  • using window.addEventListener insted of document.addEventListener
  • using DOMContentLoaded like this document.addEventListener("DOMContentLoaded", function(event) {});
  • using window.onload = function() {}

Solution 2:

The event you're looking for is "DOMContentLoaded", not "load"

document.addEventListener('DOMContentLoaded', function () {
  console.log('loaded')
})

Solution 3:

Because document.onload isn't called? could use window.onload, or if you have jQuery, use jQuery(document).ready(function(){...})

Solution 4:

It will be helpful to read the MDN about this useCapture option: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

useCaptureOptional A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. Events that are bubbling upward through the tree will not trigger a listener designated to use capture. Event bubbling and capturing are two ways of propagating events which occur in an element that is nested within another element, when both elements have registered a handle for that event. The event propagation mode determines the order in which elements receive the event. See DOM Level 3 Events and JavaScript Event order for a detailed explanation. If not specified, useCapture defaults to false.

It will be additionally helpful to read this post about directionality of event propagation: Unable to understand useCapture attribute in addEventListener

The capture phase: the event is dispatched to the target's ancestors from the root of the tree to the direct parent of the target node.

The target phase: the event is dispatched to the target node.

The bubbling phase: the event is dispatched to the target's ancestors from the direct parent of the target node to the root of the tree.

useCapture indicates for which phases the event travel will be on:

If true, useCapture indicates that the user wishes to add the event listener for the capture phase only, i.e. this event listener will not be triggered during the target and bubbling phases.

If false, the event listener will only be triggered during the target and bubbling phases.

I am not certain how this pertains to your code, but this will indicate why it isn't working correctly for the load event.

I imagine it is because the document is the root node, so it has no parents.

Post a Comment for "Why Is Addeventlistener Load Preventing Code From Working?"