views:

174

answers:

1

I have a scrollable div tag (overflow). Now I'd like to use mouse to click and hold and move to navigate up and down (like how the hand cursor feature in Adobe Reader works).

Is there any js script to achieve this? Specifically, I'm using jquery, any jquery plugins to achieve this?

+2  A: 

Don't know about any plugins but this shouldn't be too hard:

$(function() {
    $('#foo').mousedown(function(e) {
        var start = e.pageY;
        var startPos = $(this).scrollTop();
        var el = $(this);

        $().mousemove(function(e) {
            var offset = start - e.pageY;
            el.scrollTop(startPos + offset);
            return false;
        });

        $().one('mouseup', function(e) {
            $().unbind();
        });

        // Only if you want to prevent text selection
        return false;
    });
});

A working example can be found here:

http://www.ulmanen.fi/stuff/mousescroll.php

Tatu Ulmanen
Great. Exactly what I'm looking for. Thanks a lot!
huy
Now have another problem when trying to put another div box on top of #foo (greater z-index). The code works for that div box as well. Do you know how to remove that?
huy
You have to stop event propagation from the nested elements - when you click on a nested element, the mousedown event gets propagated back to the `#foo` element. Easy way to solve this is to use `$('#foo *').click(function() { return false; });`. This snippet stops event propagation from all the children of `#foo`. This may not be desired in all cases but should work for you.
Tatu Ulmanen
that wouldn't work. I did a event.stopPropagation() instead :-)
huy
huy, that has the same effect as `return false;`.
Tatu Ulmanen
I remember `return false;` skipped the default behavior of the event
huy