4

I want to place an element on an absolute position on the screen, so that it stays in (roughly) the same position, even when the browser window is moved (not scrolled). Is such a thing even possible?

alexgolec
  • 26,898
  • 33
  • 107
  • 159
  • 6
    @WaleedKhan Have you read the question? – VisioN Mar 05 '13 at 19:31
  • 2
    you can use the `window.screenX` and `window.screenY` to calculate the offset – Josh Mar 05 '13 at 19:34
  • @Josh Besides you need to [imitate window move event](http://stackoverflow.com/q/4319487/1249581). – VisioN Mar 05 '13 at 19:36
  • See [here][1] it looks a little bit problematic. [1]: http://stackoverflow.com/questions/2337795/screen-coordinates-of-a-element-via-javascript – idoo Mar 05 '13 at 19:38
  • @VisioN i dont have the time to write the full code now. i was just giving a hint so somebody can take it from here – Josh Mar 05 '13 at 19:40

1 Answers1

4

Maybe not the most optimized solution, but you could use an interval to check the window.screenX and window.screenY (as suggested in the comments). Then, when those values change, update the position using the difference from the last position. Something like:

function setPosition(el, x, y) {
    var style = window.getComputedStyle(el);
    el.style.left = parseInt(style.left) + x + "px";
    el.style.top = parseInt(style.top) + y + "px";
}

var sX = window.screenX,
    sY = window.screenY,
    box = document.getElementById("box");

var interval = setInterval(function() {
    if (window.screenX !== sX || window.screenY !== sY) {
        setPosition(box, sX - window.screenX, sY - window.screenY);
        sX = window.screenX;
        sY = window.screenY;
    }
}, 1000/30);

Here is an example of JSFiddle. It's a bit choppy on Chrome.

Corey
  • 5,818
  • 2
  • 24
  • 37
  • 1
    Very nice! One thing: maximizing the window seems to throw off the positioning. Any idea if that can be corrected for? I presume it would need to become aware of window resizings? – alexgolec Mar 05 '13 at 23:35
  • Yes, you would have to create a method of handling the resize as well. – Corey Mar 06 '13 at 15:24