Search code examples
javascriptcssangularjsonmousemove

How to align ngMouseMove event calculation with my div


I've created a custom slider which you can see at the following fiddle: http://jsfiddle.net/dorcohen/tf8aj7sj/

I'm trying to align the mouse cursor with the ngMouseMouse movementX element at the following way:

$scope.dragInProgress = function (event) {
    if ($scope.inProgress) { 
            $scope.level += Math.ceil(event.movementX);
        }
    };

The problem is that I can't understand how I can put my cursor on the div all the time (taking into consideration the movement direction and speed.


Solution

  • As per this answer it seems to (thankfully) not be possible to change mouse pointer position.

    However I think that you've approached the problem from the wrong side. If I read you correctly the goal of keeping the pointer position in sync with dragging handle is to make user experience more pleasant.

    There's an easy workaround for lack of such DOM API though. The trick is to attach the mousemove event at the document level allowing the mouse position to move freely.

    In other words you would change the dragStarted to:

    var mousmove = function(event) {
        $scope.$apply(function() {
            $scope.dragInProgress(event);
        });
    };
    var target;
    $scope.dragStarted = function(event) {
        target = event.target;
        $document[0].addEventListener('mousemove', mousmove);
        $scope.inProgress = true;
    };
    

    And then use the mousemove event to calculate the new slider position:

    $scope.dragInProgress = function(event) {
        if ($scope.inProgress) {
            var markerBox = target.getBoundingClientRect();
            var containerBox = target.parentNode.getBoundingClientRect();
            var space = containerBox.width;
            var x = event.clientX;
            var percentage = (Math.min(Math.max(containerBox.left, x), containerBox.right) - containerBox.left) / space;
            $scope.level = percentage * 100;
        }
    };
    

    Here's an updated fiddle.