Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to avoid changing between CSS cursor types while dragging a small element?

Specifically in a case like a user dragging the handle of a slider and the cursor momentarily (due to snapping) or longer (due to off axis drag) changes from the cursor specified in the css of the handle because the mouse is no longer over the handle. I've created an example to illustrate the issue.

How can I avoid this?


EDIT

Stephen Thomas's answer isn't sufficient because different elements might have different icons e.g. a horizontal slider handler getting ew-resize and a vertical one getting ns-resize and I haven't seen a way to reliably determine what to 'lock' the cursor to.


EDIT the second

With some minor changes to Jacob Grey's answer I figured out something that serves my needs. My tweak adds a css rule that I can toggle on <body> to force all descendant elements to inherit its cursor. This example shows the difference in behavior between Jacob Grey's solution and my tweaked solution.

<style> body.dragging { cursor: inherit !important; } </style>

<script>
    var disableDragCursorOverride = function() {
        $("body").removeClass("dragging");             
        $("html").css("cursor","auto")
                 .off("mouseup", disableDragCursorOverride);
    };

    $(selectorForDraggable).on("mousedown",function(e){
        var cursor = $(e.target).css("cursor");
        $("body").addClass("dragging");
        $("html").css("cursor",cursor)
                 .on("mouseup", disableDragCursorOverride);
    });
</script>
like image 877
Bjartr Avatar asked Jul 06 '26 23:07

Bjartr


2 Answers

Not a lot of details in the question, but as a general approach:

Define a CSS rule something like:

.dragging {
    cursor: pointer; /* or whatever */
}

When dragging starts, add that class to the <body> or some parent container:

$('body').addClass('dragging');

When dragging ends, remove the class:

$('body').removeClass('dragging');
like image 95
Stephen Thomas Avatar answered Jul 09 '26 14:07

Stephen Thomas


Yes, it is very easily possible. As Stephen Thomas said, you can just add it to the body, but you want the cursor to be what ever you clicked on. That can be done like:

$('.slider').on("mousedown",function(e){
    var cursor = $(e.target).css("cursor");
    $("body").css("cursor",cursor);
});
$('body').on("mouseup",function(e){
    $("body").css("cursor","auto");
});

That jQuery will get the cursor for what you click on, and add it to the body, as long as the mouse is down.

JSFiddle Demo

like image 33
Jacob Gray Avatar answered Jul 09 '26 15:07

Jacob Gray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!