Search code examples
javascriptjqueryhtmlcsscursor

Changing the cursor while it's not moving


so I have a webapplication (in html,css and javascript, jquery) that drags an element around (meaning, the cursor doesn't move over that element since the element is moving with the cursor). I wish to change the cursor to a 'move' cursor, but I'm encountering this weird behaviour. I wrote this bit of code to demonstrate:

<html>
<head></head>
<body oncontextmenu="return false;">
    <script>
        var b=document.getElementsByTagName('body')[0];
        b.onmousedown=function(event){
            if(event.button){
                b.style.cursor='move';
            }
        }
        b.onmouseup=function(event){
            if(event.button){
                b.style.cursor='initial';
            }               
        }
    </script>
</body>
</html>

So basically, I want the cursor to changing to 'cursor:move;' whenever the user is holding the right mouse button; But, the following happens:

  • initial: cursor: default
  • mouse down: cursor: default
  • mouse move: cursor: default
  • mouse up: cursor: move
  • mouse move: cursor: default

so now my question is: why does this happen, and what would be a good way to fix it?

PS: tested in chrome, this is the main browser I need this to work in


Solution

  • http://jsbin.com/vepihik/edit?html,css,js,output

    document.addEventListener('mousedown', onMouseAction)
    document.addEventListener('mouseup', onMouseAction)
    
    function onMouseAction(e){
        document.body.style.cursor = e.buttons && e.button == 2 ? 'move' : 'default';        
    }
    html, body{ height:100%; }
    Try to hold the RIGHT mouse button and move it, then release

    Attaching the mousedown and mouseup events on the document itself and making them both call the same function which simply check the button clicked. right = 2 in your case.