When using a div element with position fixed and overflow scroll, the window scroll event in JQuery may not be triggered as expected

What is the reason for window scroll not being detected with elements in position fixed, despite having the overflow: scroll; property in the CSS?

If the condition is as follows:

<!doctype html>
<html>

<head>
  <style>
    body {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }
    
    #a {
      position: fixed;
      background: red;
      height: 100px;
      width: 100%;
      text-align: center;
    }
    
    #aa {
      display: inline-block;
    }
    
    #b {
      top: 100px;
      position: fixed;
      overflow: scroll;
      width: 100%;
      padding: 0;
      /* height is setted with JS but for simulate it's setted manually */
      height: 500px;
      -webkit-transition: top 0.3s;
    }
    
    #c {
      /* height is setted with JS */
    }
  </style>
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
  <script>
    $("*").on("scroll", function(e) {
      console.log("scrolling");
    })
    $("window").on("scroll", function(e) {
      console.log("scrolling");
    })
  </script>
</head>

<body>

  <header>
    <div id="a">
      <div id="aa">
        <h1>Hello</h1>
      </div>
    </div>
  </header>



  <main>
    <div id="b">
      <div id="c">
        F&1W8xyaOkA1ksfM9Dp
        <br> q2%aKsbDUlE1@GvE4v
        <br> XKCMcpA4bxmGpZIPAT0
        <br> cxL0tQ5t7zt!b&rVNL!
        <br> v3@6LANuuQ^n1swb)6c
        <br> L6o&6llTkqLGOuh(oug
        <br> CoDDa76!bkDw2Hn%ZCX
        <br> uuGcqIr(bVPHR*^!v&y
        <br> Ld&q&Y9G@w5XZKZcARL
        <br> 5k1!eJmacWe5kJbDj!r
        <br> HTSRtSTAKCDEy2MjK*c
        <br> Nq^&cTlUcan&oSDNGtc
        <br> P%J(LRZHir7d7iPVfN7
        <br> chbGfzkrxI2eXvCszH2
        <br> yl1dMbEQ4ycI5R4U&1
        <br> 5h42cd8XxOCcGdk)fCw
        <br> mEniGshHPHsTSMV9Zi
        <br> )1Yk!&VrFlqt(pEOSl6
        <br> s!enwOf@7RCErVgfG0s
        <br> Rks!cx!Y(5ixDX()R
        <br> 7ZxOmEeJYmHcoQkv4BC
        <br> FneHbodv*wS)*Q7a*A&
        <br> 4T4!D*J5^V9L&UHoiB
        <br> fnHgaK!1D6Slm)TO&MF
        <br> fBV%%4)H0i6stle)EFg
        <br> *aa&w%D9aS@1NbO(GS9
        <br> b!zwIVJtv4Ihi!%6XGj
        <br> 34)fvxWYpB3Alovj^1)
        <br> 4HvY5MmeUaOaf&Kktl
        <br> 6zIdvB(@lTiXwQzgB^Y
        <br> HkcQ*U5xNl(E6z5@l
        <br> ByM6jeZjGl%2K7Wv!HM
        <br> 4OSC*HcGW9gJ@E%MS5E
        <br> kNZ9WdbpHx3gqecIjqn
        <br> vayBp^o7^8NdztFVySS
        <br> AO&diq^*Y3PnyEand!r
        <br> YgVu@GHQhxbCsH73I56
        <br> T^0KLQwScvig)okXwKN
        <br> G94(ScoX&U5XA9o1cgI
        <br> r&^xZLvawH)^1qETka0
        <br> LWHs%*TX!PBiPwPDsnt
        <br> QZTDpVCwwGyxCk7s6pd
        <br> 6NO8a8vpJmbf*Cc^%c2
        <br> zmkIrV@XJxaywe7f^V&
        <br> rREWV&3vrBdb(1wWTav
        <br> df*z83KfPilOJhQD8vP
        <br> AZil1GPzZxq5U6!SDJg
        <br> eoW6Q2gm1kDw251W(Nx
        <br> S66wLAW6X1(0zfQ5W2
        <br> mAs54R9q1inHMkU6(4E
      </div>
      
      
      <footer>
        <center><h2>Footer</h2></center>
      </footer>
      
    </div>
    
  </main>
  <nav>
    position fixed (left side with JS)
  </nav>
  <script>
      document.querySelectorAll("*").forEach(element => element.addEventListener("scroll", ({
      target
    }) => console.log('Scrolling ', target, target.id)));
  </script>
</body>

</html>

Why does querySelectorAll("*") log the scroll while JQuery does not? What is the solution to detecting scroll in the current layout using JQuery?

How can scrolling be detected with the current layout using JQuery at the beginning of the file?


Edit (for better understanding):

What method can be used to detect scrolling with the current layout in JQuery from the start of the file?

Answer №1

The scroll event is not being detected for the window since the scrolling occurs within the div. Only the div is scrolling, not the window.

Your other code, which adds the scroll event listener to each element, is also not capturing the event because it is located in the head of the document before any elements are loaded.

To address this issue, I have relocated that section of your script to the bottom of the document.

<!doctype html>
<html>

  <head>
    <style>
      body {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }

      #a {
        position: fixed;
        background: red;
        height: 100px;
        width: 100%;
        text-align: center;
      }

      #aa {
        display: inline-block;
      }

      #b {
        top: 100px;
        position: fixed;
        overflow: scroll;
        width: 100%;
        padding: 0;
        /* height is setted with JS but for simulate it's setted manually */
        height: 500px;
        -webkit-transition: top 0.3s;
      }

      #c {
        /* height is setted with JS */
      }

    </style>
    <script src="https://code.jquery.com/jquery-3.6.1.js"></script>
    
  </head>

  <body>

    <header>
      <div id="a">
        <div id="aa">
          <h1>Hello</h1>
        </div>
      </div>
    </header>



    <main>
      <div id="b">
        <div id="c">
          F&1W8xyaOkA1ksfM9Dp
          <br> q2%aKsbDUlE1@GvE4v
          <br> XKCMcpA4bxmGpZIPAT0
          <br> cxL0tQ5t7zt!b&rVNL!
          <br> v3@6LANuuQ^n1swb)6c
          <br> L...
        </div>


        <footer>
          <center>
            <h2>Footer</h2>
          </center>
        </footer>

      </div>

    </main>
    <nav>
      position fixed (left side with JS)
    </nav>
    <script>
      $(window).on("scroll", function(e) {
        console.log("scrolling");
      })

    </script>
    <script>
      document.querySelectorAll("*").forEach(element => element.addEventListener("scroll", ({
        target
      }) => console.log('Scrolling ', target)));

    </script>
  </body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to resize a Bootstrap 4 form to perfectly fit the screen width in mobile view?

I need help with a Bootstrap 4 form that I want to adjust to fit the viewport of mobile users. Currently, mobile users see this: https://i.sstatic.net/JjRa8.png The form inputs do not fill the width of the screen, and I want them to take up the full wid ...

Activate current event on newly added elements

Is it possible to have both blur and keypress(13) trigger the same action on an appended element? I thought using trigger() would work, but it's not. Hopefully, I'm just missing something obvious. $(document).ready (function() { $("#btn").cli ...

Why does the data loaded from PHP using jQuery vanish suddenly?

After conducting a thorough search to avoid duplication, I couldn't find a similar post, so my apologies in advance if there is one. Here is my current issue: Why does the data, as shown in the code below, load momentarily and then disappear? CSS ...

jQuery sorting function is utilized to organize a table after its rows have been modified through an ajax

My website features an election section that displays updated election numbers in real-time. Previously, users had to refresh the page to see new results. I have implemented code that utilizes a custom REST API to fetch live numbers and jQuery to dynamica ...

Prevent image element from overflowing in HTML

How can I prevent the images on the right from extending beyond the right padding? I want the fourth image to align with the red block above it. https://i.sstatic.net/KUE62.png Does that clarify things? <div style="margin: 0 15px;height: 40px; back ...

Troubleshooting Issue with Ionic's UI Router

Recently, I created a basic Ionic app to gain a better understanding of UI router functionality. To my surprise, when I ran the app, nothing appeared on the screen. Additionally, the developer tools in Google Chrome did not show any errors or information. ...

Encountering issues with Monaco Editor's autocomplete functionality in React

I'm facing an issue with implementing autocomplete in the Monaco Editor using a file called tf.d.ts that contains all the definitions in TypeScript. Despite several attempts, the autocomplete feature is not working as expected. import React, { useRef, ...

Is there a way to arrange two columns in a horizontal line?

The alignment of the columns is off: https://i.sstatic.net/1l4CO.png The issue: https://i.sstatic.net/Iokm9.jpg I am looking to create a blog layout with 2 columns: one column for the main content, displaying articles the other column as a menu To a ...

Creating a Sudoku puzzle grid with HTML and CSS - a step-by-step guide

Apologies for the basic inquiry, but I have created a sudoku grid with the following structure. Modified(Using Tables): <table id="grid" border="1" style="border-collapse: collapse;"> <tr class="row"> ...

Troubleshooting Issue: Vue.js and Firebase not synchronized after deleting document

I am currently developing a web application that allows users to add and remove notifications. To facilitate the deletion process in Firestore, I have included an ID field in the notification document, which is also added to the data-id attribute in the D ...

The async-await status is resolved, however the ajax request is still pending

Currently, I am attempting to handle a getJson call and process the data received. Despite trying various solutions such as using $.ajax's async: false (which did not work due to the query being cross domain), callbacks, and the .done portion of a bas ...

Examples of panel splitting using Ajax

Looking for recommendations on a tutorial or framework that focuses on creating split panels using Ajax and PHP. The goal is to have two panels, with panel 1 containing a menu that opens content in panel 2 when clicked. Despite numerous searches on Googl ...

The comparison between createElement() and AJAX response

Currently, my website has a login form that updates the page with user data through AJAX after successful login. To maintain semantic integrity, I use JavaScript to remove the login form from the page once the user is logged in. However, when the user lo ...

What is the process for obtaining a descriptor for a JavaScript class constructor function?

Is there a way to retrieve the body of the constructor method of a JavaScript class without parsing the entire class body? I am currently creating a custom wrapper for Express to dynamically generate routes, and I am interested in accessing only the constr ...

After successfully uploading a file, refresh the file list using AngularJS, DropzoneJS, and JSON

In my "file manager page," I am using DropzoneJS for uploading files and AngularJS ng-repeat to display all the saved files. The file list is retrieved through an ng-controller that uses an http.get request to fetch a JSON file with the file list. When Dr ...

Creating a responsive website that utilizes YAML and is optimized for extremely narrow screen widths

I have noticed that my responsive design using YAML is working well for the most part. However, on screens with very small widths, the YAML grids become extremely tiny. In such cases, it would be more practical to have the right grid displayed below the le ...

Inconsistencies with AJAX performance

Hey there, I'm a newbie and absolutely loving this site! Currently diving into the world of JavaScript and have been through numerous tutorials. However, I seem to be struggling with getting Ajax to work. Recently stumbled upon this code snippet on ...

What is the best way to empty an input field after adding an item to an array?

In my Angular 2 example, I have created a simple functionality where users can add items to an array. When the user types something and clicks the button, the input is added to the array and displayed in a list. I am currently encountering two issues: 1 ...

"Enhance your web development experience with the combination of best_in

I'm currently utilizing the best_in_place gem within my rails application to enable inline editing functionality. However, I am encountering difficulties when attempting to display text as HTML safe. When the text is not specified as html_safe, this ...

How can Angular incorporate an external JavaScript library?

I'm currently facing an issue with importing libraries like popper, jquery, and chart.js into my Angular project. After downloading them through the CLI, I made sure to reference them in both my index.html and angular.json files. index.html <hea ...