Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine user scroll vs JavaScript scrollTop change

Tags:

javascript

How can I determine if a scroll event was caused by my own animation, or it was caused by a user's scroll?


I have a scrollable area, which acts like a CV control knob, where the user can scroll and directly map to a DOM element's size, left, and top

If a scroll event ends inside specific bounds, I want to "snap" to a nearby position, with a granular tween that modifies the same scrollable area's scrollTop.

While this transition is occurring, I want any user scroll to immediately override the animation, so that the user regains control


I feel like I'm very close to a solution, and I noticed that my usecase involves floating point increments, where a user scroll will only increase by full integers. I'm not sure if this is useful, and it feels like a hack to abuse, but I'm really looking for ANY WAY that I can discriminate between a user scrollTop change, and my animation's scrollTop change

like image 438
neaumusic Avatar asked Nov 20 '25 07:11

neaumusic


1 Answers

I was stuck at something I was doing in my project and I needed to detect whether user is scrolling or is it that our code that is scrolling.I used a global variable myVar which changes its value depending on scroll events. FIDDLE

Here is the code.

var myVar = false;
$("#button").click(function() {
  myVar = true;
  $('html, body').animate({
    scrollTop: $("#bottom").offset().top
  }, 2000);
});
$(window).bind('mousewheel DOMMouseScroll', function(event) {
  myVar = false;
});
$(document).scroll(function() {
  console.log('Scroll initiated by ' + (myVar == true ? "user" : "browser"));
});
div:hover {
  text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span> hello there </span>
<br/>
<div id="button"> click here to go down </div>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<div id="bottom"> just sitting </div>
like image 199
shubham agrawal Avatar answered Nov 22 '25 19:11

shubham agrawal