DOM Event - Scroll


scroll is an view event that happens when the user scroll

If you want to disable scrolling, don't forget to disable the key up and down. See keydown block


Pure Javascript

  • A function that tells when the element is visible (in the view port)
function isElementVisible(el) {
    const rect = el.getBoundingClientRect(),
        vWidth = window.innerWidth || document.documentElement.clientWidth,
        vHeight = window.innerHeight || document.documentElement.clientHeight,
        efp = function (x, y) {
            return document.elementFromPoint(x, y)

    // Return false if it's not in the viewport
    if (rect.right < 0 || rect.bottom < 0
        || rect.left > vWidth || > vHeight)
        return false;

    // Return true if any of its four corners are visible
    return (
        ||  el.contains(efp(rect.right,
        ||  el.contains(efp(rect.right, rect.bottom))
        ||  el.contains(efp(rect.left,  rect.bottom))
  • Scroll is a really sensitive and CPU intensive function. Therefore, the execution of the callback function should be limited. The below example shows the use if the requestAnimationFrame that executes its own callback function either to:
let lastKnownScrollPosition = 0;
let ticking = false;

const pSelected = document.querySelectorAll('p');

document.addEventListener('scroll', function(e) {

  if (!ticking) {
    window.requestAnimationFrame(function() {
      for (i = 0; i < pSelected.length; i++) {
             let p = pSelected[i];
             if (isElementVisible(p)) {
                  p.innerHTML = '<p>'+p.innerText+' - In view</p>';
      ticking = false;

    ticking = true;
  • HTML to scroll
  • Just scroll to see the result


Extracted from the scroll jquery reference.

  • Create many p element to overflow the iframe
$( "p" ).clone().appendTo( document.body );
$( "p" ).clone().appendTo( document.body );
$( "p" ).clone().appendTo( document.body );
$( "p" ).clone().appendTo( document.body );
  • The real scroll work that set the display css property to inline to show the span element that is by default not displayed
$( window ).scroll(function() {
  $( "span" ).css( "display", "inline" ).fadeOut( "slow" );
  • The HTML element with the cached span element that will be revealed when scrolling and a little bit of content to overflow the iframe.
<p>p - <span>Scroll happened!</span></p>
  • The css to cache the span element
span { display: none; }
  • Just scroll the below iframe



The mouse wheel will not propagate to the parent avoiding that the page is going upward when in a textarea

Documentation / Reference

Powered by ComboStrap