Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fix div to screen

In my project I want to fix a div element to a certain position on the screen. Not the window, the screen. So if the browser is resized the div stays put and if the browser is moved the div stays put. Possible?

Here is my basic html page that contains just a dot at the center of the screen.

#dot {
    width: 8px;
    height: 8px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    background: #000;
    position:relative;
    left: -4px;
    top:-4px;
}
<div style="position: absolute; top: 50%; left: 50%;">
    <div id="dot"></div>
</div>

I know I can use window.screenX and window.screenY and then do some math to ensure the position is set to give the illusion of a fixed element, however that would require polling the window position every millisecond to detect when the browser is moved (which is probably pretty heavy and rare anyways). The plan is to do this with much more than just a dot...

Any ideas? I'm completely stumped.

like image 584
mrg95 Avatar asked Oct 18 '22 15:10

mrg95


2 Answers

Since window.screenX and window.screenY are only accessible in JS, there is really no way to do this other than polling the variables and changing the css using javascript.

like image 60
Tennyson H Avatar answered Oct 31 '22 10:10

Tennyson H


I think you can use requestAnimationFrame, which is better for this sort of tasks than setInterval, to keep an eye on window.screenX and window.screenY and also to move (animate) the point div if those numbers change:

var x = window.screenX,
    y = window.screenY;

function moveDot() {
    if(x !== window.screenX || y !== window.screenY)
        console.log('move dot');

    x = window.screenX;
    y = window.screenY;
}

(function animloop(){
    window.requestAnimationFrame(animloop);
    moveDot();
})();

Here's the Can I Use link for requestAnimationFrame.

like image 36
a.guerrero.g87 Avatar answered Oct 31 '22 11:10

a.guerrero.g87