Last active
October 3, 2016 01:36
-
-
Save mattdanielbrown/bc0f83c49f586214f3f7a23f485cf131 to your computer and use it in GitHub Desktop.
Grab current scroll position (including horizontal axis). Set overflow to hidden (retain previous overflow value). Scroll document to stored scroll position with scrollTo(). *** THIS REQUIRES JQUERY. ***
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // | |
| // This Requires jQuery | |
| // | |
| // | |
| var scrollIsEnabled; // scroll state varialbe | |
| scrollIsEnabled = true; // by default, scroll is enabled | |
| // lock scroll position, but retain settings for later | |
| function disableScroll() { | |
| // save page offsets | |
| var scrollPosition = [ | |
| self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft, | |
| self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop | |
| ]; | |
| // get the html object | |
| var html = jQuery('html'); // it would make more sense to apply this to body, but IE7 won't have that | |
| html.data('scroll-position', scrollPosition); | |
| html.data('previous-overflow', html.css('overflow')); | |
| html.css('overflow', 'hidden'); | |
| window.scrollTo(scrollPosition[0], scrollPosition[1]); | |
| } | |
| // un-lock scroll position | |
| function enableScroll() { | |
| var html = jQuery('html'); | |
| var scrollPosition = html.data('scroll-position'); | |
| html.css('overflow', html.data('previous-overflow')); | |
| window.scrollTo(scrollPosition[0], scrollPosition[1]); | |
| } | |
| /** | |
| * | |
| * This is the function to place inside an event/another function, | |
| * or edit it to be an event itself. | |
| * | |
| **/ | |
| // Check scroll state and take appropriate action | |
| function toggleScroll() { | |
| // Check if scroll is enabled | |
| if(scrollIsEnabled === true) { | |
| // It is, so disable it | |
| disableScroll(); | |
| // and update the current scroll state | |
| scrollIsEnabled = false; | |
| } else { | |
| // It is not, so enable it | |
| enableScroll(); | |
| // and update the current scroll state | |
| scrollIsEnabled = true; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment