digglemister digglemister - 4 months ago 14
HTML Question

Issues using custom cursor with draggable element

Ok, so I have a draggable element that is contained by it's parent. I'm trying to add a custom cursor while dragging, including when the cursor moves off of the draggable element itself. And then when dragging stops, on

mouseup
, the cursor should return to
default
.

<div id="container">
<div class="draggable"></div>
</div>





$(document).ready(function() {

$(window).on("mouseup", function() {
$("*").removeClass("customcursor");
})

$(".draggable").on("mousedown", function() {
$("*").addClass("customcursor");
})

$(".draggable").draggable({
containment: "parent",
});
});





html {
background: lightblue;
}

body {
background-color: teal;
}

#container {
height: 400px;
width: 400px;
background-color: black;
}

.draggable {
height: 200px;
width: 200px;
background-color: red;
}

.customcursor {
cursor: url(http://media.fluke.com/images/8-icon-30x30.gif), default;
}


Here is a working fiddle.

However, this is giving me two issues.

First issue: While dragging, when the cursor moves onto the
body
element, the custom cursor is no longer in effect. However, when the cursor moves onto the html element, the custom cursor does work. Admittedly, this can be solved by adding a wrapper element, so the cursor is never on the
body
, but I'm still perplexed about why this is happening.

Second issue: After dragging for the first time, the cursor gets stuck with the custom cursor, even though the
.customcursor
class has been removed. This second issue can be solved if I add
.customcursor
class on the
start
and
stop
events of the draggable rather than on
mousedown
and
mouseup
, but I wanted the custom cursor on
mousedown
even if the draggable isn't moved.

If anyone has some insight into why these issues are occurring or good ways to fix them, I'd really appreciate the help.

Answer

Add !important to the the cursor change:

.customcursor {
    cursor: url(http://media.fluke.com/images/8-icon-30x30.gif), default !important;
}

The body was being overrode by a direct element style:

element.style {
    cursor: auto;
}

Also, for some reason, the cursor is being left behind as a direct style even after the class is removed. Remove it with JavaScript or jQuery:

$(window).on("mouseup", function() {
    $("*").removeClass("customcursor");
    //document.body.style.cursor = "";
    $("body").css("cursor", "")
    console.log("mouseup");
})

Fiddle: https://jsfiddle.net/ntyuuqq2/

Comments