Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed background regardless of browser position (explanation picture included!)

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:

enter image description here

(Explaination for picture: Red outline is browser window, the light blue-transparent picture is the position and size that the picture should always have)

like image 794
user3163104 Avatar asked Oct 02 '22 23:10

user3163104


1 Answers

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);
})()
like image 155
Pointy Avatar answered Oct 22 '22 08:10

Pointy