Question

When the mousewheel is scrolled on the body of a page this event can be captured. I'd like this event to trigger a target element to scroll.

#target is a scrollable element that is never the height of the page. I'd like to capture the mousescroll event anywhere on the page so even if the cursor is not over the element the element still scrolls.

$( 'body' ).on( 'DOMMouseScroll mousewheel', function () {
    // Scroll #target instead of body    
});

Thanks to this post for showing me how to capture scroll wheel events: Capturing Scroll Wheel Events

Was it helpful?

Solution

You can have a look at this.

http://jsfiddle.net/ZtGva/7/

JS

$(function () {
    var myCounter = 0,
        myOtherCounter = 0;
    var scroll = 0;

    $("#target").scroll(function () {
        myCounter = myCounter + 1;
        $("#log").html("<div>Handler for .scroll() called " + myCounter + " times.</div>");
    });

    //Firefox
    // $(document).bind(...) this works as well
    $('#body').bind('DOMMouseScroll', function (e) {
        if (e.originalEvent.detail > 0) {
            scrollDown();
        } else {
            scrollUp();
        }

        //prevent page fom scrolling
        return false;
    });

    //IE, Opera, Safari
    $('#body').bind('mousewheel', function (e) {
        if (e.originalEvent.wheelDelta < 0) {
            scrollDown();
        } else {
            scrollUp();
        }
        //prevent page fom scrolling
        return false;
    });

    function scrollDown() {
        //scroll down
        console.log('Down ' + scroll);
        if (scroll < $('#target').find('div').height() - $('#target').height() + 20) {
            scroll = $('#target').scrollTop() + 5;
            $('#target').scrollTop(scroll);
        }
    };

    function scrollUp() {
        //scroll up
        console.log('Up ' + scroll);
        if (scroll > 0) {
            scroll = $('#target').scrollTop() - 5;
            $('#target').scrollTop(scroll);
        }
    };
});

Note I added a div for height calculation

<div id="target"><div>.... </div></div>

You can clean up this code a bit by caching some jquery variables but the idea is there

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top