Switch up the cursor style as you move the mouse

Encountering an unusual error where trying to add a "moving" class to an element while moving/dragging the mouse. Using jQuery 3.1.1 on Chrome 59.0.3071.115.

Simplified down to this example:

<html>
<head>
<style>
    .thing {
        display: block;
        width: 10em;
        height: 10em;
        background: green;
    }
    .moving {
        cursor: move;
    }
</style>
<script src="jquery-3.1.1.min.js"></script>
</head>
<body>
<div class="thing"></div>
<script>
    $(document).ready(function(){
        var $thing = $('.thing');
        $thing.on('mousedown', function(e){
            $thing.addClass("moving");
            console.log("mousedown");
        }).on('mouseup', function(e){
            $thing.removeClass("moving");
            console.log("mouseup");
        });
    });
</script>
</body>
</html>

A green box displayed on the page, triggering events when clicking and releasing the mouse on it.

Observations:

  1. Click on the green box -- The "moving" class applied to div (visible in Chrome Developer Tools), but cursor remains arrow instead of expected move cursor.
  2. Dragging without click -- Cursor stays as default arrow.
  3. Release click on the green div -- Cursor briefly switches to move cursor then reverts to default if mouse moved slightly.

Attempted solutions from sources like with no success. Different CSS selectors, elements tried, issue persists outside jsfiddle environment.

Edit

Potential browser bug found, resolved by closing and reopening Chrome. Any known bugs in Chrome causing this behavior?

Answer №1

An alternative approach : (no need for JavaScript)

  • Utilize the tabindex attribute
  • CSS selector: :active:hover

.element {
  display: block;
  width: 10em;
  height: 10em;
  background: green;
  user-select: none;
  outline: none;
}

.element:active:hover {
  cursor: move;
  background: red;
}
<div class="element" tabindex="1"></div>

Answer №2

dragging doesn't equal to mousedown event

This behavior is the default dragging action of browsers. To include the drag event, combine it with the mousedown event.

$(document).ready(function() {
  var $thing = $('.thing');
  $thing.on('mousedown ,drag', function(e) {
    $thing.addClass("moving");
    console.log("mousedown");
  }).on('mouseup', function(e) {
    $thing.removeClass("moving");
    console.log("mouseup");
  });
});
.thing {
  display: block;
  width: 10em;
  height: 10em;
  background: green;
}

.moving {
  cursor: move;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="thing"></div>

Answer №3

After encountering similar issues as described above, I stumbled upon this helpful solution while using standard Javascript instead of jQuery. Surprisingly, even six years later and with Chrome version 120, the fix remains unchanged: simply close and restart the browser to resolve the problems. Merely reloading the page, with or without clearing the cache, proves ineffective - a full browser restart is necessary. This indicates that the bug still persists in the code. Sharing this information for anyone else facing the same challenges...

Answer №4

$(document).ready(function() {
    // Event listener added for mousemove on the document
    $(document).on('mousemove', function(event) {
      // Cursor style set to 'pointer'
     $('body').css('cursor', 'pointer');

      // Additional logic can be included based on mouse position or other conditions
      // For instance, change cursor to 'default' when not over a specific area
      // if (event.clientX < 100 || event.clientY < 100) {
      //   $('body').css('cursor', 'default');
      // }
    });

This code snippet changes the cursor style to 'pointer' while the mouse is in motion. To alter the cursor style, replace 'pointer' with other valid CSS cursor values like 'default', 'pointer', etc.

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

Why is it that JavaScript files are not fetched when injecting HTML into the DOM?

Currently, I am developing a login process and initiating an ajax post request from the browser. After performing some logic to verify the user’s credentials in the backend using asp.net core, I return a view which represents the application's homep ...

Is there a way to add a blur effect to the moving elements in the background of a

For a project I'm currently working on involving a full screen styled Google Maps page, I am looking for a way (css, jQuery, or other options...) to overlay a header and slide-in sidebar with a blur effect similar to the iOS frosted/blur effect. I am ...

Varying spacing among elements with identical classes

I'm facing some styling issues. My goal is to ensure that each h3 tag has the same distance between the bottom border of its container (marked with a pink border) and the bottom border of its parent (indicated in the image below): https://i.sstatic.ne ...

Exploring Node.js with a straightforward illustration and tackling the EPERM error

const server = require('http').createServer(function(req, res){ }); server.listen(8080); This code snippet is causing an error to be displayed in the console: $ node node_server.js node.js:201 throw e; // process.nextTick error, or &apos ...

Is there a way to add two identical classes to one CSS file at the same time?

I currently have two CSS files. Is there a way to combine them into a single CSS file without making any changes to the original files? File 1: .class1{ background-color: red;} File 2: .class1{ background-color: blue;} ...

Revamping ng-model in AngularJS

Here is my scenario: cols = [{field="product.productId"},{field="product.productPrice"}]; data = {products:[{product:{productId:1,productPrice:10}, {product:{productId:2, productPrice:15}}]} This is what I want to achieve: <div ng-repeat="product in ...

Interacting with Forms Using Ajax

I require some assistance. I am attempting to use ajax to 'POST' form elements. When I retrieve all elements by name, I can see the results in the browser console and the data is successfully sent to the databases. However, the issue is that it ...

Is it possible to adjust the height of a panel in Jquery Mobile 1.4.5?

Currently working on a jqm project that is specifically for mobile devices. In this project, I have implemented two panels - one set to push and the other overlay. While one panel is positioned in the left corner of the screen, the other is located in the ...

Is coffeescript supported by Moovweb?

Lately, I've been researching the Moovweb platform and I'm curious about its compatibility with CoffeeScript. Could someone share a code example to demonstrate how Moovweb works with CoffeeScript? ...

Can you please provide me with information on how I can send messages to US numbers using a toll-free number?

I attempted to utilize this code in the SNS console, but it showed a failure. I am seeking guidance on how to send a message using a TFN number. async sendMessage(testId: number) { const mobileNo = test.customer.phoneNo; const params = { Message: ...

transform CSV rows into JavaScript entities

I have a CSV file titled "people.csv" that contains information about individuals. fname, lname, uid, phone, address John, Doe, 1, 444-555-6666, 34 dead rd Jane, Doe, 2, 555-444-7777, 24 dead rd Jimmy, James, 3, 111-222-3333, 60 alive way My goal is to e ...

Exploring the Core Component of React Js with Testing

Below is how I export the root component in React JS: export default connect(mapStateToProps, mapDispatchToProps)(HomePage); This is how I import the component in my mocha test file: import HomePage from '../components/study/HomePage'; In my ...

Using $.ajax to make asynchronous requests in ASP.NET Web Forms

I am currently working on incorporating the $.ajax method into my sample program. The structure of the page is as follows: <form id="form1" runat="server"> <div> Country: <asp:TextBox ID="txtCountry" runat="s ...

Display and conceal panel with the press of the asp:button

Initially, the panel is hidden. I am looking to display the panel when the <asp:button is clicked. Here is my code: <asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="167px" data-ico ...

Edit the contents within HTML strings without altering the HTML structure

If I have a string of HTML, it might look something like this... <h2>Header</h2><p>all the <span class="bright">content</span> here</p> I am interested in manipulating the string by reversing all the words. For example ...

Storing css data for iPhone Facebook application

Currently, I am in the process of developing a webpage specifically for the iPhone Facebook app wall link. Interestingly, when attempting to apply the margin attribute to a div within the webpage, the margin doesn't seem to have any effect when clicki ...

Is there a way to save a base64 image to an excel file?

I need assistance with exporting Excel Charts from NVd3 using Angularjs. Here is the code I have been trying: (jsfiddle) <button id="myButtonControlID">Export Table data into Excel</button> <div id="divTableDataHolder"> <table> ...

Ways to modify or add styles to p tags using the Document Object Model (DOM)

I am trying to change the font size variable in my P tag using the DOM, but I am struggling to find a way to access it and modify the styles. I attempted the following code: document.body.p.style.font-size = ""+p_var+"px"; I have also tried using various ...

What is the threshold for leveraging Node.js when implementing efficient filtering of JavaScript objects across multiple array indexes?

Seeking practical and theoretical insights for my application. Consider 50,000 js objects, each with 5 properties: 0: Object CostCenter: "1174" Country: "USA" Job: "110-Article Search" Team: "Financial" Username: "anderson" Also, there are 5 a ...

What happens if I forget to include "await" in an asynchronous function call? Will the task still finish executing?

Looking for advice on handling asynchronous operations in Javascript and the latest Node.JS. I have a scenario where I need to make an HTTP call using the Axios library, and I'm not concerned about the result of the operation. Whether it succeeds or ...