Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript `onscroll` event standalone (without frameworks)

Tags:

javascript

I need a standalone JavaScript onscroll event handler (without frameworks such as jQuery, Prototype, mootools, etc.), which is also cross browser.

I have searched for one, I can only find thousands of examples using jQuery or Prototype.

like image 411
Tiberiu-Ionuț Stan Avatar asked Jun 06 '12 11:06

Tiberiu-Ionuț Stan


People also ask

What is onScroll event?

The onscroll event occurs when an element's scrollbar is being scrolled. Tip: use the CSS overflow style property to create a scrollbar for an element.

Do scroll events 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 can I tell if someone is scrolling?

To detect if a user is scrolling with JavaScript, we can watch for scroll events by adding event handlers. to add the userHasScrolled variable. Then we set the window. onscroll property to a function that runs when we scroll.


2 Answers

From element.addEventListener:

    function onScrollEventHandler(ev)
    {
        alert(ev);
        //http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#event-type-scroll
    } 

    var el=window;

    if(el.addEventListener)
        el.addEventListener('scroll', onScrollEventHandler, false);   
    else if (el.attachEvent)
        el.attachEvent('onscroll', onScrollEventHandler); 
like image 162
Tiberiu-Ionuț Stan Avatar answered Sep 20 '22 16:09

Tiberiu-Ionuț Stan


See it on MDN:

https://developer.mozilla.org/en/DOM/window.onscroll

window.onscroll = function (e) {
  // called when the window is scrolled.
}
like image 39
Sarfraz Avatar answered Sep 17 '22 16:09

Sarfraz