Search code examples
javascriptcursor

Replace cursor with an HTML element


Using JavaScript, is it possible to replace the cursor with an HTML element (such as a div or canvas) instead of a custom image? It would be useful in some scenarios to replace the cursor with an HTML element other than an image, but I currently don't know of any way to do this.


Solution

  • Here is a solution in jQuery, which you could see as an advantage or disadvantage. The reason I used jQuery is its cross-browser mouse position support and powerful + easy .css function.

    The Code (Javascript)

    var ElementCursor = {
        cursorElement: "",
        setCursor: function (cursorId) {
            $('html').css({
                'cursor': 'none',
            });
            ElementCursor.cursorElement = cursorId;
            ElementCursor.updateCursor();
        },
        removeCursor: function () {
            $('html').css({
                'cursor': ''
            });
            ElementCursor.cursorElement = '';
        },
        updateCursor: function () {
            $(document).mousemove(function (e) {
                $('#' + ElementCursor.cursorElement).css({
                    'position': 'fixed',
                    'user-select': 'none',
                    'top': e.pageY + 2 + 'px',
                    'left': e.pageX + 2 + 'px'
                });
            });
        }
    };
    
    ElementCursor.setCursor("cursor");
    

    After you add that to your Javascript, you can simply call ElementCursor.setCursor(id_of_your_cursor_element_here) and it will automagically replace the cursor with that element. Don't want that cursor anymore? Call ElementCursor.removeCursor() and be on your way.