Activate click events when button is being held down

I'm currently working on a directive that shifts an element to the right whenever clicked. However, I want the element to keep moving as long as the button is 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);
        }
    };
})

My question is how can I continuously detect when the button is being pressed every half second and recall the move function? Is there a way to achieve smooth movement?

Check out an interactive demo here: http://jsfiddle.net/vtortola/2m8vD/

I am unable to use jQuery for this particular task, but I am open to utilizing AngularJS modules like ngTouch or any other alternative.

Answer №1

I created a simple mockup demonstrating a solution to your issue using mouseup and mousedown events along with the $timeout service.

.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);
            });
        }
    };
})

Check out the updated demo here: http://jsfiddle.net/2m8vD/12/

You can easily adjust the timeout delay and pixel movement for smoother motion according to your preference.

Instead of using mouseup and mousedown events, you can also utilize Angular directives ng-mouseup and ng-mousedown directly bound to the button element.

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

UPDATE:
Introduced moveOnce() function for single-click functionality.

Answer №2

@Aaronias pointed me in the right direction, big thanks to him.

I successfully achieved fluid movement while holding down the button and made it cancellable when the mouse moves out. The key was eliminating the CSS transition, initiating an interval for incremental steps, and stopping that interval on mouseout or mouseup events.

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);

Here is the working version of the example: http://jsfiddle.net/vtortola/2m8vD/22/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Angularjs to bind an array element within an ng-repeat inside a directive

Having trouble displaying the elements of an array using ng-repeat with a directive. The binding is not working correctly and showing empty values. To view the code, visit http://jsfiddle.net/qrdk9sp5/ Here is the HTML: <div ng-app="app" ng-controlle ...

Using jQuery's sortable functionality to rearrange rows in a table can cause conflicts with Angular's orderBy feature

In the past, my angular app used a table with orderBy to sort rows based on a specific column. By clicking on a table header, the orderBy arguments would change and the list would be sorted according to the values in that column. Now, I am experimenting w ...

Tips for getting the setInterval function to work with a progress bar even when a tab is not in focus

After browsing through similar questions, I couldn't find the answer I was looking for. As a newbie in programming experimenting with JavaScript Progress Bar, I encountered an issue where the progress bar would pause and the counter wouldn't coun ...

What are the steps to position this bootstrap drop-down menu above a fixed page header?

Could someone please advise on what changes need to be made in the code snippet below from http://jsfiddle.net/ufkkdbja/? I am looking to ensure that when the hamburger menu is clicked, the entire menu appears without being cut off by the fixed page header ...

The value returned by $(this).next() is undefined

I'm struggling to implement jQuery functionality to toggle the display of a div, but I am encountering an issue where my jQuery code is unable to select it. Every time I try, it returns undefined. Can anyone provide assistance? $(document).on(&apos ...

Make sure to remain in the same division area when refreshing the page

Whenever I click the next button and move to step 2, I want the page to stay on the same div even after reloading. The two divs used are join_form_1 and join_form_2 Currently, when I reload the page, it reverts back to the first div. Is there a way to e ...

Bookmarklet does not successfully inject jQuery on a specific webpage

Trying to utilize a certain bookmarklet: javascript:void((function(doc){if(typeof jQuery=='undefined'){var script_jQuery=document.createElement('script');script_jQuery.setAttribute('src','https://code.jquery.com/jquery ...

Is there a way to determine if the browser window is currently in use?

The code I am currently working with looks like this: let focus; function setFocus() { focus = true; } function hideWindow() { focus = false; } window.onfocus = setFocus(); window.onblur = hideWindow(); The intention behind this code is to use it in the ...

Retrieve all string values from an Angular POST request using Express

Here is a simple code snippet that sends a POST request to a server using express: $http.post('/blah', { boolean: true, stringBoolean: 'true', number: 213, stringNubmer: '44444444', string: 'adssd&apo ...

Rendering a ImageBitMap/Image on an OffScreenCanvas using a web-worker

In my vue.js application, I have implemented vue-workers/web-workers to handle image processing tasks such as scaling and cropping in the background after a user uploads images. Due to the lack of support for Canvas and Image Object in web workers, I opte ...

Working with Vue.js: Utilizing computed properties to iterate through a JSON data structure and generate a new

This is a computed property in Vue.js: shopCart() { var scart = [], group, node; scart.push({ payMethod: 0, transactionReference: "", RoomNumber: 0, addressId: 0, deliveryMinutes ...

Tips for updating state in response to changes in props

I am working on a project where I have a Parent component that renders a large form. The Parent component has child components Child1 - Child4, which are responsible for rendering input fields. Whenever the props of the Parent component change, I need to ...

Node.js is throwing an error "Unexpected token v in JSON at position 0" which

I'm currently working on developing PHP code within the Google App Engine flexible environment. Specifically, I am facing some challenges in setting up the Firebase SDK Admin for the web version. My main struggle lies with the following block of code ...

What makes Nuxt/auth so highly secure?

Picture this scenario: a visitor lands on your Nuxt.js website's homepage. They proceed to authenticate themselves using @nuxtjs/auth-next. After successfully logging in, they gain access to a protected page meant exclusively for authenticated users. ...

Upon clicking on a different div, a div will elegantly slide down from above the footer

I'm struggling with sliding a div from the bottom of the page. Here is my JSFIDDLE Currently, when I click on the blue box (arrow-hover), the div slides up (box-main). However, to hide the div (box-main) again, I have to click inside the box-main d ...

Guide on Implementing Right-to-Left (RTL) Support in Material UI React

Currently, I am in the process of developing an application designed for LTR usage, but I am interested in adding RTL support as well. The application itself is built on top of Material UI React. By using CSS Flex Box, I have managed to rotate the applicat ...

ReactJS Enhancements: Additional Selection Feature

Is there a way to access both {board.id} and {board.name} properties in my select value? I tried using example={board.name} but it didn't work. handleChange(event){ this.setState({value: event.target.value}); this.setState({examp ...

The term 'Buffer' is not recognized in the context of react-native

Having trouble using buffer in my react-native app (developed with the expo tool). I have a hex value representing a geography Point like this for example -> 0101000020E61000003868AF3E1E0A494046B3B27DC8F73640 and I'm attempting to decode it into l ...

Looking to retrieve the text content of an element using jQuery?

My goal is to use jQuery mobile to transfer a user to a linked page when they click on an <li> element, and then display an alert with the text of the list element they clicked. However, my current implementation only shows an empty alert box. < ...

Locate a specific class inside a div and switch the CSS style to hide one element and reveal another

I have two divs, each containing a span. By default, the display of each span class is set to none. My goal is to toggle the display property of the span within the clicked div. If the span is already visible, I want to hide it; if it's hidden, I want ...