Trigger events at the click of a button

I create a directive that moves the element to the right. In each click, the element moves to the right, but I would like the element to move so long that I hold the button pressed.

.directive("car", function(){
    return {
        restrict:"A",
        link:function(scope,element,attrs,controller){
            var left=0;
            var car = angular.element(element[0].querySelector('.car'));
            var move = function(e){
                left+=10;
                car[0].style.left = left+"px";
            };
            element.on("click", move);
        }
    };
})

So, how can I determine when a button is pressed every half second and calls a function again move? Is it possible to have a smooth movement?

There is an interactive demo here: http://jsfiddle.net/vtortola/2m8vD/

I can't use jQuery for this, but I can use AngularJS modules like ngTouch or something else.

+4
source share
2 answers

@ , .

, . CSS, , , .

var move = function(e){
    if(interval)
        return;

    step(e);
    mustStop = false;

    interval = $interval(function(){
        step(e);
        if(mustStop){
            $interval.cancel(interval);
            mustStop = false;
            interval = null;
        }
    }, 10);
};

var stop = function(){ mustStop= true;};

right.on("mousedown", move)
    .on("mouseup", stop)
    .on("mouseout", stop);

left.on("mousedown", move)
    .on("mouseup", stop)
    .on("mouseout", stop);

, : http://jsfiddle.net/vtortola/2m8vD/22/

0

, mouseup mousedown timeout.

.directive("car", function($timeout){
    return {
        restrict:"A",
        link:function(scope,element,attrs,controller){
            var left=0;
            var car = angular.element(element[0].querySelector('.car'));
            var timeout;
            var moveOnce= function() {
                left+=10;
                car[0].style.left = left+"px";
            };
            var move = function(e){
                $timeout.cancel(timeout);
                timeout = $timeout(function(){
                    moveALittle();
                    move();
                }, 250);
            };
            var stop = function(e){
                $timeout.cancel(timeout);
            };
            element.on("click", moveOnce);
            element.on("mousedown", move);
            element.on("mouseup", stop);

            element.on("$destroy",function(){
                element.off("click",moveOnce);
                element.off("mousedown", move);
                element.off("mouseup", stop);
            });
        }
    };
})

: http://jsfiddle.net/2m8vD/12/

, , .

mouseup mousedown angular ng-mouseup ng-mousedown, .

<button ng-mousedown="move" ng-mouseup="stop">Move</button>

UPDATE:
​​ moveOnce(), .

+3

Source: https://habr.com/ru/post/1547644/


All Articles