0

The scroll event doesn't fire when I scroll down. Not sure what I am doing wrong here.

Below is my code:

<style>
  #scroll {
    max-height: 100px;
    overflow-y: auto;
    width: 647px;
    margin: auto;
  }
</style>
<body>
  <div id='scroll'>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
  </div>
  <script>
    $(document).on("scroll", "#scroll", function() {
      console.log("hi");
    });
  </script>
</body>
Rayon
  • 36,219
  • 4
  • 49
  • 76
json5
  • 3
  • 2
  • 1
    Have you included jquery ? a good way of checking it is to open developer tools in your browser. – Rohit Sep 15 '16 at 04:50
  • Is `scroll` being appeared ? I don't think with such a small content, `scroll` will appear... – Rayon Sep 15 '16 at 04:52
  • Possible duplicate of [why doesn't delegate work for scroll?](http://stackoverflow.com/questions/9253904/why-doesnt-delegate-work-for-scroll) – t.niese Sep 15 '16 at 05:19

2 Answers2

2

Scroll events do not bubble for elements: MDN: Events scroll

Bubbles Not on elements, but bubbles to the default view when fired on the document

Because of that you cannot use event delegation. You always need to add the event listener directly to the element on which that event happens:

$('#scroll').on('scroll', function() {
}

Or use vanilla JavaScript and capture the event in the capturing phase as described here: [...]But, on modern browsers (IE>8), you can capture scroll event to e.g document level or any static container for dynamic element.[...]

Community
  • 1
  • 1
t.niese
  • 39,256
  • 9
  • 74
  • 101
0

this is how you can detect the scrolling and scroll position.hope this will help to you. refer this working demo.scroll to see.

<!DOCTYPE html>
<html>
<head>
 <title></title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
 
</head>

<style type="text/css">
body{
 height: 1000px;
}

div#scroll{
 width: 300px;
 height: 200px;
 overflow: scroll;
 background-color: orange;
 color: white;
 text-align: center;
 font-size: 20px;
 font-family: monospace;
}

</style>


<body>
 <div id="scroll">
  <li>one one</li>
  <li>one one</li>
  <li>one one</li>
  <li>one one</li>
  <li>one one</li>
  <li>one one</li>
  <li>one one</li>
  <li>one one</li>
  <li>one one</li>
  <li>one one</li>
  <li>one one</li>
  <li>one one</li>
 </div>

</body>

<script type="text/javascript">

$("div#scroll").scroll(function(){
 alert("scrolling");
 var scrollPosition = $(this).scrollTop();
 alert(scrollPosition);
});



</script>
</html>
caldera.sac
  • 4,918
  • 7
  • 37
  • 69