Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom cursor outside of browser window

I have a element on my website which is freely resizable. This is done by 4 handles on the edges. On hovering these handles and while resizing the element I want to show the respective resize arrows.

Currently I implemented this behavior by setting the css cursor style of the body/root to these arrows. The problem about it is the limit to the client area of the browser window. It would be visually more consistent and less confusing, if the arrow cursor would be visible everywhere while the mouse is hold down.

Google Maps is doing the same thing with their hand cursor while moving the map. So my question is how to achive this effect on my own.

My current (relevant) source:

function startObjectScaling(e){
    e.stopPropagation();
    e.preventDefault();
    document.documentElement.style.cursor = this.style.cursor;
    window.addEventListener("mouseup", stopObjectScaling, false);
}

function stopObjectScaling(e){
    e.stopPropagation();
    document.documentElement.style.cursor = '';
    window.removeEventListener("mouseup", stopObjectScaling);
}

[...]

var tg = document.getElementById("transformGadget");
var handle = tg.firstChild.nextSibling;
for(var i=0;i<4;i++){
    handle.addEventListener("mousedown", startObjectScaling, false);
    handle = handle.nextSibling;
}
like image 646
V02460 Avatar asked Nov 01 '10 23:11

V02460


1 Answers

There is a special function implemented in the more modern browsers for this purpose. The name is setCapture(). It redirects all mouse input to the object the method was called on. Now a simple css cursor definition on that element is enough to archive the desired effect. After mouse release this effect stops (for security for sure). It can also be stopped manually by calling releaseCapture

example:

<style type="text/css">
#testObj {
    /* this cursor will also stay outside the window.
       could be set by the script at the mousedown event as well */
    cursor: hand;
}
</style>

[...]

document.getElementById('testObj').onmousedown = function(e){

    // these 2 might be useful in this context as well
    //e.stopPropagation();
    //e.preventDefault();

    // here is the magic
    e.target.setCapture();
}
like image 67
V02460 Avatar answered Sep 23 '22 09:09

V02460