Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I know whether the scroll of the user is UP or DOWN?

I want to determine the scroll of the users. I'm using jQuery.. And jquery have .scroll event.. But the .scroll event can't determine whether the user is scrolling the page downwards or upwards.

like image 462
Keira Nighly Avatar asked May 02 '09 03:05

Keira Nighly


3 Answers

Here is an example with plain javascript:

var previousPosition = window.pageYOffset || document.documentElement.scrollTop;

window.onscroll = function() {
  var currentPosition = window.pageYOffset || document.documentElement.scrollTop;

  if (previousPosition > currentPosition) {
    console.log('scrolling up');
  } else {
    console.log('scrolling down');
  }

  previousPosition = currentPosition;
};
<h1>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda perferendis consequuntur sunt possimus rem iusto necessitatibus dignissimos odio nam vel quia vitae voluptates quibusdam quidem, maxime mollitia perspiciatis, ipsum veritatis!</h1><h1>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda perferendis consequuntur sunt possimus rem iusto necessitatibus dignissimos odio nam vel quia vitae voluptates quibusdam quidem, maxime mollitia perspiciatis, ipsum veritatis!</h1><h1>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda perferendis consequuntur sunt possimus rem iusto necessitatibus dignissimos odio nam vel quia vitae voluptates quibusdam quidem, maxime mollitia perspiciatis, ipsum veritatis!</h1><h1>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda perferendis consequuntur sunt possimus rem iusto necessitatibus dignissimos odio nam vel quia vitae voluptates quibusdam quidem, maxime mollitia perspiciatis, ipsum veritatis!</h1>
like image 93
Sgnl Avatar answered Oct 16 '22 09:10

Sgnl


FASTEST WAY IN PURE JS

let position = window.pageYOffset; // get current page-Y-offset

window.addEventListener('scroll', () => { // Listen for scroll

let scroll = window.pageYOffset; // get page-Y-offset value with every scroll

//If the scroll is greater than position, user has scrolled down, else they scrolled up
scroll > position ? console.log('down') : console.log('up');

//Set the position equal to scroll
position = scroll;

});

Here is a simple example.

//The message variable is specific to this example
const message = document.querySelector('.message');

let position = window.pageYOffset;

  window.addEventListener('scroll', () => {
    let scroll = window.pageYOffset;
    
    scroll > position ? message.innerHTML = 'Scrolled Down' : message.innerHTML = 'Scrolled Up';
    position = scroll;
  });
.container {
  postion: relative;
  width: 100%;
  height: 200vh;
  background: linear-gradient(red,blue);
}

.container .message {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 50px;
  color: white;
  font-size: 2em;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1em 0;
}
<div class="container">
  <div class="message">Scroll down and up</div>
</div>
like image 43
Michiel J Otto Avatar answered Oct 16 '22 10:10

Michiel J Otto


You can start with a variable like this:

var position = $(window).scrollTop(); // should start at 0

And then have something that monitors whether the scrollTop is going up or down:

$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  if (scroll > position) {
    console.log("scrolling downwards");
  } else {
    console.log("scrolling upwards");
  }
  position = scroll;
});

var position = $(window).scrollTop();

$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  if (scroll > position) {
    console.log("scrolling downwards");
  } else {
    console.log("scrolling upwards");
  }
  position = scroll;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p style="font-size: 40px;">

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vitae erat et lacus facilisis hendrerit ac nec lectus. Aenean hendrerit maximus tempus. Phasellus feugiat odio vitae ligula eleifend condimentum. Vestibulum id faucibus magna, sit amet
  consequat nunc. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum pellentesque, magna ut ultricies lacinia, nisi dui condimentum ante, vitae euismod arcu eros vitae nulla. Donec finibus erat sed libero
  commodo tincidunt. Curabitur pulvinar, nisl vitae tempus commodo, felis nisi pretium arcu, sed gravida risus sapien eu ipsum. In metus magna, consequat eleifend sem a, condimentum imperdiet augue. Fusce blandit dui eu erat lacinia, vitae laoreet orci
  porttitor. Nulla tortor nibh, porttitor at augue quis, elementum hendrerit velit. Fusce at risus in massa pellentesque dapibus id ut velit. In tempor magna vitae diam posuere pharetra. Aliquam sed semper sem. Nam dapibus pretium tempus. Interdum et
  malesuada fames ac ante ipsum primis in faucibus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Cras ex odio, auctor eget mauris eget, dignissim rutrum mauris. Nulla porttitor leo nec enim gravida scelerisque. Nam consectetur malesuada
  enim eu tincidunt. Morbi posuere imperdiet nisl. Aenean non tortor porttitor, aliquam lectus a, scelerisque risus. Donec eu felis non justo sollicitudin venenatis eget eu mauris. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam fringilla
  mi ut purus ornare, et interdum est accumsan. Donec dapibus enim non sem dictum pretium. Pellentesque quis velit sem. Duis rutrum vulputate sem eget fringilla. Pellentesque vel enim nulla. Aliquam erat volutpat. Maecenas lacinia condimentum semper.
  Quisque gravida orci ut mauris rhoncus interdum. Pellentesque id augue vitae leo accumsan vehicula. Fusce sed justo id metus ornare ultrices. Vestibulum gravida lacus vitae finibus viverra. Maecenas dapibus quam et pulvinar tempus. Maecenas at molestie
  justo. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vivamus non elementum dui, a rutrum ligula. Ut ut odio feugiat, suscipit arcu eget, feugiat leo. Nunc elit erat, ultricies vel volutpat vitae, dignissim
  vel nunc. Sed pharetra lacus sem, quis dignissim metus ullamcorper a. Vivamus ac augue libero. Donec consectetur sem non ipsum faucibus cursus. Morbi facilisis efficitur urna sit amet vehicula. Proin nec finibus magna. Cras suscipit nec eros sit amet
  vestibulum. Integer aliquam a mauris non interdum. Fusce eu mattis enim. Vestibulum congue ullamcorper velit ut tempus. Curabitur et pretium massa, ac condimentum massa.
</p>
like image 26
Paolo Bergantino Avatar answered Oct 16 '22 08:10

Paolo Bergantino