Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why could a check if (document.addEventListener) returns false

On what basis does a check if (document.addEventListener) return false? Is there a way we can change this?

like image 560
Miroo Avatar asked Oct 11 '10 15:10

Miroo


People also ask

What does false mean in addEventListener?

addEventListener("click", first, true); when clicking child element, first method will be called before second . By default, the useCapture flag is set to false which means you handler will only be called during event bubbling phase.

Does addEventListener return anything?

The addEventListener() method (when applied to the document object of the JavaScript DOM) attaches an event handler to the document. It has the following syntax with the following parameters. It does not return any value.

How do I check if addEventListener exists?

To check whether dynamically attached event listener exists or not with JavaScript, we can get and set the element's listener attribute. export const attachEvent = ( element: Element, eventName: string, callback: () => void ) => { if (element && eventName && element. getAttribute("listener") !== "true") { element.

How do you fix addEventListener is not a function?

To solve the "addEventListener is not a function" error, make sure to call the addEventListener() method on a valid DOM element, or the document or window objects, and place the JS script tag at the bottom of the body tag in your HTML. Copied!


2 Answers

If this code snippet returns false, this means that the addEventListener method property is not support by the browser. This is the case for Internet Explorer, where attachEvent is used instead:

if (document.addEventListener){  
  document.addEventListener(...);
} else if (document.attachEvent){  
  document.attachEvent(...);  
}
like image 160
Romain Linsolas Avatar answered Oct 28 '22 20:10

Romain Linsolas


if (document.addEventListener) evaluates to false if there's no addEventListener method in document. This check is usually done to see if you can use this method to attach event to DOM element (works in most browsers except IE).

is there a way we can change this ?
This question I don't completely understand. Probably, you want something like document.attachEvent('onload', callback); for IE. You can't really add addEventListener method to document (well, maybe you can, but it wouldn't make sense).

Docs for addEventListener

like image 37
Nikita Rybak Avatar answered Oct 28 '22 21:10

Nikita Rybak