I am working on a UI that uses horizontal scrolling in a div element (using overflow: scroll). I cannot scroll to the left, because it would start the
Piggy backing off of https://github.com/micho/jQuery.preventMacBackScroll posted by micho I have made this possible in both safari and chrome. Also, I made it work for both left scrolling and right scrolling.
(Sorry that this is in coffeescript. It wouldn't be hard to translate back into javascript)
$(document).on 'ready', ->
# This code is only valid for Mac
if !navigator.userAgent.match(/Macintosh/)
return
# Detect browsers
# http://stackoverflow.com/questions/5899783/detect-safari-using-jquery
is_chrome = navigator.userAgent.indexOf('Chrome') > -1
is_safari = navigator.userAgent.indexOf("Safari") > -1
is_firefox = navigator.userAgent.indexOf('Firefox') > -1
# Handle scroll events in Chrome, Safari, and Firefox
if is_chrome || is_safari || is_firefox
$(window).on 'mousewheel', (event) ->
dX = event.deltaX || event.originalEvent.deltaX
dY = event.deltaY || event.originalEvent.deltaY
# If none of the parents can be scrolled right when we try to scroll right
prevent_right = dX > 0 && $(event.target)
.parents().addBack()
.filter ->
return this.scrollWidth - this.clientWidth != 0 &&
$(this).scrollLeft() < this.scrollWidth - this.clientWidth &&
($(this).css('overflow-y') == 'scroll' || $(this).css('overflow-y') == 'auto')
.length == 0
# If none of the parents can be scrolled left when we try to scroll left
prevent_left = dX < 0 && $(event.target)
.parents().addBack()
.filter ->
return $(this).scrollLeft() > 0
.length == 0
# If none of the parents can be scrolled up when we try to scroll up
prevent_up = dY > 0 && !$(event.target)
.parents().addBack()
.filter ->
return $(this).scrollTop() > 0
.length == 0
# Prevent minute left and right scroll from messing up vertical scroll
if (prevent_right || prevent_left) && Math.abs(dY) > 5 && !prevent_up
return
# Prevent futile scroll, which would trigger the Back/Next page event
if prevent_left || prevent_up || prevent_right
event.preventDefault()