2

Quick disclaimer–I know there are similar questions but they don't provide the answer I'm looking for.

I'm trying to disable scrolling entirely when the page loads but still be able to listen to when user attempts to scroll. The goal is to trigger an animation function when user attempts to scroll and once the animation completes, the scroll would be re-enabled back to it's normal state.

I've tried to disable scroll and play my animation after user tries to scroll like this:

function blogHeaderMagic() {
 //disable scroll function
 disableScroll()
 //my animation and on a callback you'll see I call allowScroll function to allow scroll normally once animation completes
 TweenMax.to("#post-hero-media-wrapper", 1, {height:54, onComplete: allowScroll });
 scrolled = true
 }

document.onscroll = function() {
if( scrolled == false){
    blogHeaderMagic();
}
}

And while this works great, in Chrome or Safari, it isn't such a smooth effect because when user first attempts to scroll, scroll is enabled so they can scroll like 100px from the top and only then scroll locks. This is why I would first like to disable the scroll and when user attempts to scroll (although they won't be able to) I would like to detect their attempt to scroll and trigger my animation function on that detection. Is this possible?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
beliy333
  • 479
  • 11
  • 23

1 Answers1

1

Answer

You could set the body tag to overflow:hidden; which won't allow the user to scroll and use these event handler, then put back the overflow property to whatever it was (probably auto if you didn't changed it in the first place).

// IE9, Chrome, Safari, Opera
document.body.addEventListener("mousewheel", MouseWheelHandler, false);
// Firefox
document.body.addEventListener("DOMMouseScroll", MouseWheelHandler, false);

function MouseWheelHandler() {
    alert('scrolling with the mouse');
    document.body.style.overflow = 'auto'
    document.body.removeEventListener("mousewheel", MouseWheelHandler, false);
    document.body.removeEventListener("DOMMouseScroll", MouseWheelHandler, false);
}

Interesting links

I did a quick codepen example. See here

Also this article

Edit----------------

Also found this Stack Overflow question

I dont think that there is a pure JS way of disabling all scroll while still detecting scroll events from the user (just reread your question) that's why I think the overflow solution is the simplest/most elegant solution (that I could come up with).

You could always detect scroll the set the scroll position to the top with something like window.scroll(0,0) and/or window.scrollTo(0,0). From what I have tested it doesn't seem to work quite well.

Community
  • 1
  • 1
Raphael Parent
  • 474
  • 5
  • 9