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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With