Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why body.addEventListener('scroll') doesn't work while body.onscroll works

Tags:

javascript

dom

I've just come across interesting behavior:

document.body.addEventListener('scroll', f)
document.body.onscroll = f;

When scrolling body, the callback is not triggered in first case and is working fine in the second. Does anyone know the reason for that?

I first assumed that the event is produced on document, however then body.onscroll should not be triggered.

Here is the plunker.

like image 614
Max Koretskyi Avatar asked Apr 26 '17 10:04

Max Koretskyi


People also ask

How do you trigger a scroll event in react?

To handle the onScroll event in React: Set the onScroll prop on an element or add an event listener on the window object. Provide an event handler function. Access relevant properties on the event or window objects.

Does scroll event bubble?

The scroll event does not bubble up. Although the event does not bubble, browsers fire a scroll event on both document and window when the user scrolls the entire page.

How do I throttle scroll an event?

You could write a simple throttle debounce function to limit the times per second the scroll event will be handled. function debounce(method, delay) { clearTimeout(method. _tId); method. _tId= setTimeout(function(){ method(); }, delay); } $(window).


1 Answers

Discussed here: Scroll listener on body

You could do it another way:

document.addEventListener("scroll", f);
like image 187
webbm Avatar answered Oct 13 '22 10:10

webbm