How to prevent a browser from going back/forward in history when scrolling horizontally?

前端 未结 5 1860
长发绾君心
长发绾君心 2020-12-09 17:39

How can one disable a modern browsers default functionality using JQuery or Native JS for going backwards or forwards when scrolling horizontally?

This usually happe

相关标签:
5条回答
  • 2020-12-09 18:06

    So I figured since i've created a web app, why not prompt the user for any unsaved changes which will defer the user from loosing any unsaved changes or ending up on the previous or next page in the browser history.

    Here is the solution if any one else comes across this problem like I did:

    window.onbeforeunload = function(e) {
        return 'Ask user a page leaving question here';
    }; 
    
    0 讨论(0)
  • 2020-12-09 18:09

    If you're on a mac this is caused by the Track Pad Gestures.

    System Preferences -> Trackpad -> More Gestures. 
    

    Not the JS solution you're looking for, but if you just want to prevent it for yourself you can turn the feature off.

    0 讨论(0)
  • 2020-12-09 18:15

    Works in Chrome and Safari (i.e tested with Chrome and Safari):

    // el === element on which horizontal scrolling is done 
    // (can be container of scrolled element or body or any other ancestor)
    var preventHistoryBack = function (e) {
      var delta = e.deltaX || e.wheelDeltaX;
    
      if (! delta) {
        return;
      }
    
      window.WebKitMediaKeyError /*detect safari*/ && (delta *= -1);
    
      if (((el.scrollLeft + el.offsetWidth) === el.scrollWidth && delta > 0) || (el.scrollLeft === 0 && delta < 0) ) {
        e.preventDefault();
      }
    };
    el.addEventListener('mousewheel', preventHistoryBack);
    
    0 讨论(0)
  • 2020-12-09 18:16
    history.pushState(null, null, location.href);
    window.onpopstate = function(event) {
        history.go(1);
    };
    

    Demo: http://jsfiddle.net/DerekL/RgDBQ/show/

    You won't be able to go back to the previous webpage, unless you spam the back button or hold down the back button and choose the previous entry.

    Note: onpopstate (or event onbeforeunload) doesn't seem to work on iOS.

    0 讨论(0)
  • 2020-12-09 18:23

    Here's something that may work for you using CSS' overscroll-behaviour property:

    Javascript

    document.body.style.overscrollBehaviour = "contain";
    

    CSS

    body {
        overscroll-behaviour: contain;
    }
    

    At the time of writing this, July 10th 2020, this causes scrolling left at the left-end of the page to no longer trigger a backward history-navigation.

    I'm not sure what other side-effects this will have on the rest of the user experience. I wish this could be applied inside elements, but it seems like this will only work when applied to the document body.

    0 讨论(0)
提交回复
热议问题