How to prevent the scroll event from firing after setting scrollTop when the mouse picks up the scroll bar?

I am trying to move the scroll bar down a few pixels when the user scrolls the top of the <div> . The problem is that after the scroll is clicked a few pixels (after I scroll to the top), the browser still thinks that my mouse is at the top of the <div> when my mouse is still held ( mousedown ) . This is bad as the event continues.

Features I am trying to achieve:

  1. Scroll to the top of the <div>
  2. Scrolling down a few pixels down, but the function does not start again, even if my mouse is still pointing.

I think this may be the way I discover a function through onscroll . Please check my code and see console.log() if I don't see the point.

 var wrapper = document.getElementById('scroll-box'); wrapper.onscroll = function (evt){ //detect when scroll has reached the top of the frame if(wrapper.scrollTop === 0){ console.log('top of frame'); wrapper.scrollTop += 500; } //detect when scroll has reached the bottom of the frame if(wrapper.scrollHeight - wrapper.scrollTop === wrapper.clientHeight){ console.log('bottom of frame'); } } wrapper.scrollTop += 3000; 
 .scroll-box { width: 400px; height: 300px; background-color: gray; overflow-y: scroll; } div ul li { padding: 50px; } 
 <div class="scroll-box" id="scroll-box"> <ul> <li>messages</li> <li>messages</li> <li>messages</li> <li>messages</li> <li>messages</li> <li>messages</li> <li>messages</li> <li>messages</li> <li>messages</li> </ul> </div> 
+5
source share
1 answer

As mentioned in the comments, the fact that the event will continue to shoot and register that the div is at the top is a natural result of pushing it out and then dragging quickly because the scroll bar has not been released. As far as I can see, there is no direct way to undo this interaction.

But without creating a custom scrollbar, this is probably the quickest fix, even if it's a minor hack:

Demo

 var wrapper = document.getElementById('scroll-box'), size = wrapper.clientWidth; wrapper.addEventListener('scroll', function() { if (!wrapper.scrollTop) { console.log('top of frame'); wrapper.scrollTop += 500; wrapper.setAttribute('style', 'width: ' + size + 'px; overflow: hidden'); setTimeout(function() { wrapper.removeAttribute('style'); }, 0); } }); wrapper.scrollTop += 200; 

Eliminate the scroll event by hiding the overflow for as little time as possible. And setting the clientWidth element so that it retains it in the original width so that the action is less noticeable.

+1
source

Source: https://habr.com/ru/post/1236486/


All Articles