Search code examples
javascriptjquerymouse-cursor

How to change image side of cursor on drag event using JQuery


When you drag an file on browser screen, an image appear side of mouse cursor that is windows default image. This images is various like Copy, Move and Forbide. See its at bottom.

enter image description here

How can i change image side of mouse cursor to this images using javascript or JQuery? For example when i drag a file and move mouse in undragable area, forbiden image display side of cursor.


Solution

  • You can use the dataTransfer.dropEffect property of the dragover event to set the small image besides the cursor:

    $(".targetDiv").on("dragover", function (event) {
        event.preventDefault();
        event.originalEvent.dataTransfer.dropEffect = "none"; // Shows the "forbidden" image
    });
    

    The values for that property are copy, move, link and none. You can test these values in the code snippet below. Please note that the originalEvent must be used. According to my tests, it works in Firefox and Chrome but not in IE.

    $(function () {
        $(".targetDiv").on("dragover", function (event) {
            event.preventDefault();
            event.originalEvent.dataTransfer.dropEffect = event.target.getAttribute("data-effect");
        });
    });
    .targetDiv
    {
        display: inline-block;
        border: solid 1px black;
        width: 80px;
        height: 50px;
        margin: 4px;
        text-align: center;
        line-height: 50px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>Drag a file over each block </p>
    <div>
        <div data-effect="link" class="targetDiv">Link</div>
        <div data-effect="move" class="targetDiv">Move</div>
    </div>
    <div>
        <div data-effect="copy" class="targetDiv">Copy</div>
        <div data-effect="none" class="targetDiv">None</div>
    </div>