Scrolling in div without scrolling page

The goal: Having a div on a page that scrolls with the mousewheel or a swipe, but that doesn’t scroll the page itself when the user reaches the bottom or the top. There’s a number of solutions out there – but I found them to variously work only on desktop or only on mobile, or only on certain browsers. The following Javascript/JQuery snippet, used for Chicmi, works on modern browsers and on mobile.

$(document).ready(function() {

    var touchPosY;
    var scrollableDiv = $('#the-target-div');

    scrollableDiv.bind('touchstart', function(event) {
        touchPosY = event.originalEvent.touches[0].clientY;
    });

    scrollableDiv.bind('touchmove', function(event) {
        var touchDelta = touchPosY - event.originalEvent.changedTouches[0].clientY;
        if (touchDelta > 0 && scrollableDiv.scrollTop() + scrollableDiv.height() == scrollableDiv.prop('scrollHeight')) {
            event.preventDefault();
        } else if (touchDelta < 0 && scrollableDiv.scrollTop() == 0) {
            event.preventDefault();
        }
    });

    scrollableDiv.bind('wheel', function(event) {
        if (event.originalEvent.deltaY > 0 && scrollableDiv.scrollTop() + scrollableDiv.height() == scrollableDiv.prop('scrollHeight')) {
            event.preventDefault();
        } else if (event.originalEvent.deltaY < 0 && scrollableDiv.scrollTop() == 0) {
            event.preventDefault();
        }
    });

});

jamiembrown

http://www.jamiembrown.com/

Co-founder of Chicmi.com. Consultant for some of London's most exciting tech startups.