0

This function load data from db, how to execute it when user scroll page down and scroll top

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>

   <script type="text/javascript">
        $(document).ready(function(){

            //var to auto-increment 
                var flag = 0;

                $.ajax({
                    type: "GET",
                    url: "db_load.php",
                    data:{
                        'offset': 0,
                        'limit': 3
                    },
                    success: function(data){
                        $('body').append(data);
                        flag += 3;
                    }
                });
                    }); //end document.ready function
                   </script>

I need a simple way to detect whenever user scroll down and scroll up and than call the function above

1 Answers1

2

You can set an eventListener to the window handling every scroll. This way you can determine when the scroll is at the top or at the bottom of your entire document.

Look at an example:

let limitBottom = document.documentElement.offsetHeight - window.innerHeight;
window.addEventListener("scroll",function(){
  if(document.documentElement.scrollTop == 0){
    console.log("Window scroll is at the top")
  }
  if(document.documentElement.scrollTop == limitBottom){
    console.log("Window scroll is at the bottom")
  }
})
body {
  margin: 0;
  padding: 0;
}

.x {
  background: black;
  width: 100%;
  height: 200vh;
  color: white;
}
<div class="x">SCROLL HERE</div>
k3llydev
  • 2,057
  • 2
  • 11
  • 21
  • Yes, `$(window).on("scroll",function(){/*YOUR CODE*/})` should work, since the eventListener is the only thing that might define the usage of jQuery or not. But here is where [you might not need jquery](http://youmightnotneedjquery.com/) comes in. – k3llydev Sep 02 '19 at 20:02
  • so anyway I will need the eventListener right? since my code has jquery part it should also work on the way you did't? it will be jquery inside js? should it work just fine too? –  Sep 02 '19 at 20:16
  • 1
    Thats true, jQuery or not, you will need the eventListener to handle this kind of actions. – k3llydev Sep 02 '19 at 20:20