Keep the operation going until the mouse button is no longer pressed

Is there a way to have the function below run continuously while the mouse is held down? Currently, it only executes once per click. I am looking for a solution where the function keeps running as long as the mouse button is pressed down and stops when released.

    $('#md').mousedown(function(e){
         var pCords = e.pageY +e.pageY;
         var max = $(document).height()+$(document).width();
             var dg = 2*( pCords / max );
         $('#div').css({ 'transform':'rotate('+dg+'deg) '});
    });

Answer №1

Here is a simple method to add a time delay between the execution of event handlers:

let timerId = 0;

$('#md').mousedown(function(e){
             timerId = setInterval(function() {
                         let pCords = e.pageY + e.pageY;
                         let max = $(document).height() + $(document).width();
                         let dg = 2 * (pCords / max);
                         $('#div').css({ 'transform': 'rotate(' + dg + 'deg) '});
                 }, 20); // Specify the desired time delay here
            });

$('#md').mouseup(function(e){
        clearInterval(timerId);
    });

Answer №2

The solution to this issue can be found here: jQuery continuous mousedown

To fix this, you need to create a flag that switches to true when the first mousedown event happens. Then, you should execute a function that only stops when the flag goes back to false after the mouseup event.

Answer №3

To achieve this, you can implement a basic semaphore technique. Take a look at the following code snippet:

var flag = true;

$('#md').mousedown(function() {
    flag = false;

    setTimeout(function() {
        while(!flag) {
            // Add your custom code here
        }
    }, 0);
});

$(document).mouseup(function() {
    flag = true;
});

With this approach, you can ensure smooth execution of your tasks without blocking the main process. The setTimeout function assists in creating an asynchronous flow within your code.

There might be more advanced approaches to tackle this scenario, but for now, this straightforward method should suffice. Disclaimer: I might need some coffee before exploring those options further!

Answer №4

Do you think this solution could work? You can create a global boolean variable to keep track of whether the mouse is up or down, and then continuously run your function while the mouse is down on that particular element.


var isMouseUp = false;

$(document).ready(function(){
      $('#md').mousedown(function(e){
         isMouseUp = false;
         while(!isMouseUp)
        {
            // Perform desired actions
        }
    });

    $('#md').mouseup(function(e){
        isMouseUp = true;
    });
});

--edit: Don't forget to set isMouseUp to true when the mouse is lifted. Sorry about that oversight.

Answer №5

If you want to execute a function repeatedly every second after a mousedown event, you can utilize the setTimeout method in JavaScript. Here's an example:

 $('#md').on({
        mousedown: function () {
            $(this).data('clicked', true);
            var process = function() {
                if ($(this).data('clicked')) {
                   // Your code here
                    setTimeout(process, 1000); // Run the function every 1 second
                }
            };
            process();
        },
        mouseup: function () {
            $(this).data('clicked', false);
        }
    });

Answer №6

If you want, you have the option to define the handler for the mousemove event within the mousedown event and remove it in the mouseup event as shown in the following code snippet:

function movehandler(e) {
    var pCords = e.pageY + e.pageY;
    var max = $('#md').height();
    var dg = 20 * (pCords / max);
    $('#md').css({
        'transform': 'rotate(' + dg + 'deg) '
    });
}
$('#md').mousedown(function (e) {
    $('body').on('mousemove', movehandler);
});
$('#md').mouseup(function (e) {
    $('body').off('mousemove');
});
$('body').mouseleave(function (e) {
    $('body').off('mousemove');
});

Jsfiffle The example may not be perfectly written but it conveys the idea.

UPDATE: Keep in mind that $('body').on('mousemove', may not be enough depending on your specific HTML structure.

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

I'm interested in querying my mongodb collection data based on a particular field

I need help creating a list from my mongodb database that can be sorted by the "username" field. After learning about the limitations of namespaceing in mongodb, I'm trying to figure out how to sort my collection based on the "username" field. Here ...

The iframe remains unresponsive and fails to resize as needed

I am facing an issue while trying to embed an iframe into one of my websites. It seems that the responsiveness is lost and it does not scale properly on mobile devices. You can see the issue here. Interestingly, when I place the same iframe on a plain HTM ...

The conversion from CSV to JSON using the parse function results in an inaccurate

I am having trouble converting a CSV file to JSON format. Even though I try to convert it, the resulting JSON is not valid. Here is an example of my CSV data: "timestamp","firstName","lastName","range","sName","location" "2019/03/08 12:53:47 pm GMT-4","H ...

Extract specific data points from external API responses on a webpage crafted in HTML

I require assistance on how to extract individual values from an HTML page. I received a response from the PAYU payment gateway team in HTML format, but I need to retrieve specific attribute values related to the transaction details. Below is the response ...

Tips for creating a CSS transition that reverses direction

Is there a way to create a hover effect where a border appears at the bottom of an element when it is being hovered over, and then retracts back when the mouse leaves the element? I've managed to get the border to appear on hover using CSS, but I&apos ...

When you reach a scrolling distance of over 300 vertical heights,

Is it possible to show and hide a class based on viewport height? I am familiar with displaying and hiding a class after a specified pixel height, but I'm wondering if it's achievable using viewport height instead? Specifically 3 times the viewp ...

creating a randomized location within an HTML element using JavaScript

Trying to figure out how to randomly generate a position within an HTML div. I've come up with a JavaScript function that looks like this: function randomInRange(min, max) { return(Math.floor((Math.random() * (max - min) + 1) + min)); } My ...

Using JavaScript to develop a demonstration of the capabilities of Microsoft's Cognitive

Having trouble getting this basic example of the Microsoft Cognitive Services to work in JavaScript. Need some help or a working example, please! I've attempted to run the code in both node and browser with necessary modifications. Encountering an e ...

What is the best way to place a footer at the bottom of the screen using Bootstrap 5?

I need help ensuring that the footer element always stays at the bottom of the screen, regardless of the screen size. The code I currently have works fine on mobile screens, but it appears in the middle of the screen on tablets or larger screens. Here is ...

jQuery equivalent of this script

My HTML code triggers a JavaScript function when the input is changed: <input type="file" id="file-uploaded" onchange="checkinput(this);"> The script checks if the input actually contains a file: function checkinput(input) { if (input.files &a ...

I have a quick and straightforward inquiry about JavaScript and the process of logging

I've been working on this JavaScript code that is supposed to log the information entered into the email and password fields onto the console, so I can later store it in a database. The issue I'm facing is that when I run the code for the first ...

Issue with dropdown functionality in Hartl 3rd edition chapter 8, section 2.3

When I click on the "Account" link in the navbar, the dropdown menu is not appearing. Instead, a # is being added to the end of the URL, turning users/1 into users/1#. A similar question regarding the dropdown issue has been posted here: ruby on rails cha ...

Enhance the interactive experience of your website by incorporating additional questions with multiple

I am struggling to incorporate multiple questions with various options - some questions have 2 options while others may have 3 or more. I'm encountering issues specifically with the inner box functionality. Can you please provide guidance on where I m ...

CSS: The relative positioned element now functions correctly with the inclusion of overflow-x

Is there a way to ensure that the images in the day_time_block cover the title class? I would also like all contents within the day_time_block to be displayed using overflow-x. However, when I add overflow-x: auto; to the scroll div, the images in the d ...

An inexplicable right margin

I am facing an issue with centering a table (a tracklist) under the album cover and title. There seems to be an unexpected margin on the right side that I can't seem to figure out. Any help in identifying the cause of this issue would be greatly appre ...

Problem with text alignment in Internet Explorer 7

I'm facing an issue with the alignment of columns on my website. Each item is represented by an <a> tag within an <li> element, which is part of a larger <ul>. The topmost <li> in each list has a unique class compared to the lo ...

I want to allow only numbers to be entered into a TextBox using JavaScript without the need to disable right-click

Is it possible to restrict a textbox to only allow numbers by utilizing the onkeydown event to prevent non-numeric input and disable ctrl+V? However, two issues arise: If someone right-clicks and pastes, any character can be entered. Is there a solutio ...

Link Tag and the Download Functionality in HTML

I'm looking for a way to deactivate the "download" attribute in an anchor tag, like download="false": <a href="https://cdn1.iconfinder.com/data/icons/HTML5/512/HTML_Logo.png" download></a> In my AngularJS application, I want all image fi ...

Ending a timer from a different function in a React component

Currently, I am delving into the world of React and attempting to create a timer component. While I have successfully implemented the start function for my timer, I am now faced with the challenge of stopping the timer using an onclick handler from another ...

In need of Javascript assistance for checks with if, or, and while conditions

Greetings, I am reaching out for assistance as I have hit a roadblock in my coding endeavors. Although such requests are not common for me, I am in need of guidance with the following code snippet: function insertVideo(link) { if (link) { if(link. ...