Search code examples
javascriptjqueryclickmousedown

Stop jQuery "click scroll" reset


I have a little script running so i can scroll trough a div with the mousedown option. Unfortunately it resets on each click and i can't quite figure out why it is doing this.

<script>
  $(function () {
    var clicked = false, clickX;
    $("#gallery").on({
        'mousemove': function(e) {
            clicked && updateScrollPos(e);
        },
        'mousedown': function(e) {
            clicked = true;
            clickX = e.pageX;
        },
        'mouseup': function() {
            clicked = false;
            $('html').css('cursor', 'auto');
        }
    });

    var updateScrollPos = function(e) {
        $('#gallery').scrollLeft($(window).scrollLeft() + (clickX - e.pageX));
    }
  });
</script>

I am assuming it has something to do with

clickX = e.pageX;

$('#gallery').scrollLeft($(window).scrollLeft() + (clickX - e.pageX));

Why am I? because : "Returns the horizontal coordinate of the event relative to whole document." So I am assuming it takes the original position when you click but it doesnt update when you actually scroll this. Anyone has a fix for this?

http://jsfiddle.net/fLr4d7kt/6/


Solution

  • We have fixed it like this :

    $(function () {
        var scroll = 0;
    
        $(function () {
            var clicked = false, clickX;
            $("#gallery").on({
                'mousemove': function(e) {
                    clicked && updateScrollPos(e);
                },
                'mousedown': function(e) {
                    clicked = true;
                    clickX = e.pageX;
                    scroll = $('#gallery').scrollLeft();
                },
                'mouseup': function() {
                    clicked = false;
                    $('html').css('cursor', 'auto');
                }
            });
    
            var updateScrollPos = function(e) {
                $('#gallery').scrollLeft(scroll + (clickX - e.pageX));
            }
        });
    });
    

    js: http://jsfiddle.net/fLr4d7kt/10/