If possible I would prefer to do this in HTML/CSS/JS but if not, anything goes.
I'm trying to set the background for a webpage to have a kind of absolute position that will remain there regardless of where the browser window is on the screen and regardless of size.
Picture for clarification:
(Explaination for picture: Red outline is browser window, the light blue-transparent picture is the position and size that the picture should always have)
You can get the screen position of the window with window.screenX
and window.screenY
. Then you can track that with a simple interval timer:
setInterval(function() {
$('body').css('backgroundPosition',
-window.screenX + 'px ' + -window.screenY + 'px');
}, 50);
(That uses jQuery but it's not necessary.)
Here is a jsbin to demonstrate. It's a little jumpy, but it'll probably heat up client machines as it stands so I wouldn't run the timer too much faster. The problem is that while the browser will tell you about window size changes (the "resize" event), it won't tell you via events about the window being moved around.
Here's a somewhat more efficient version without jQuery and with some checks to avoid touching the style when the window hasn't moved. This doesn't seem to make Firefox or Chrome go too nuts even running every 15 milliseconds:
(function() {
var sx = window.screenX, sy = window.screenY;
setInterval(function() {
if (window.screenX !== sx || window.screenY !== sy)
document.body.style.backgroundPosition =
-(sx = window.screenX) + 'px ' + -(sy = window.screenY) + 'px';
}, 15);
})()
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