How To: Scroll a Web-Page Background using JavaScript

Update: As per request, modified to move the background in any direction and at any speed you’d like – all you have to do is change the vertSpeed, horizSpeed, and updateDelay variables to values of your choice! Oh, and I fixed up the jitter-on-wrap-around properly to use a better way of constraining the offsets which caters for all directions without letting the offsets hit any numerical limits.

I’m teaching a course titled Produce and Manipulate Digital Images at the moment, which along with the photography and photoshop type elements you’d expect, has to include an assignment for the students to incorporate digital photography into a multimedia sequence. I can get them to do the sequence in anything I deem appropriate: Flash, JavaScript, OpenGL if I wanna.. But considering the course after this (for this particular class) is on Multimedia Web Design, I thought maybe it might be an idea to do it in JavaScript, so I had a look around for JavaScript image manipulation and found this background image scroller (link now dead unfortunately).

Only it was a bit knackered and jumped when the (hard-coded, no less) background image height was reached. So I fixed it:

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2.  
  3. <html>
  4.  
  5. <head>
  6. <!-- Original by Roy Sinclair. Update by r3dux, Nov 2010 --> 
  7. <title>JavaScript Background Scroller</title>
  8.  
  9. <script type="text/javascript">
  10. <!-- Hide script from browsers not playing nice w/ JavaScript
  11.  
  12.         // Function to scroll out background image
  13.        function scrollBackground(imageWidth, imageHeight) {
  14.  
  15.             // Set our background offset. First field is horizontal offset, 2nd is vertical
  16.             bgObject.style.backgroundPosition = horizOffset + " " + vertOffset;
  17.  
  18.             // Move image offset by given speeds
  19.             horizOffset += horizSpeed;
  20. 	    vertOffset  += vertSpeed;
  21.  
  22.             // Reset our offsets when we've gone over (under if moving left or up) the size of the background image
  23. 	    if (Math.abs(horizOffset) > imageWidth)
  24. 	    {   
  25.                 if (horizOffset > 0)
  26. 		{
  27. 			horizOffset -= imageWidth;
  28. 		}
  29. 		else
  30. 		{
  31. 			horizOffset += imageWidth;
  32. 		}
  33.             }
  34.  
  35. 	    if (Math.abs(vertOffset) > imageHeight)
  36. 	    { 
  37. 		if (horizOffset > 0)
  38. 		{
  39. 			vertOffset -= imageHeight;
  40. 		}
  41. 		else
  42. 		{
  43. 			vertOffset += imageHeight;
  44. 		}
  45.             }
  46.  
  47.        } // End of scrollBackground function
  48.  
  49. // End of JavaScript--> 
  50. </script>
  51.  
  52. </head>
  53.  
  54. <!-- Kick off the document body and use our background image -->
  55. <body background="./AU-Flag.gif">
  56.  
  57. <script type="text/javascript">
  58. <!-- Hide script from browsers not playing nice w/ JavaScript
  59.  
  60.     // Movement controlling variables:
  61.     // horizSpeed - positive values move the background to the right, negative to the left
  62.     // vertSpeed  - positive values move the background downwards, negative values move it upwards
  63.     // (Feel free to use fractional values, too i.e. 0.3 etc.)
  64.     // updateDelay - how many milliseconds to wait before updating the screen with the new background position
  65.     // (1000 ms in 1 second, lower values will move the background more often so it will appear to move faster, at the cost of increased CPU usage)
  66.     var horizSpeed = 1; 
  67.     var vertSpeed = 1.5;
  68.     var updateDelay = 50;
  69.  
  70.     // Grab our background image
  71.     var imgFile = new Image();
  72.     imgFile.src = "./AU-Flag.gif"
  73.  
  74.     // Get the height and width of the image
  75.     var imgHeight = imgFile.height;
  76.     var imgWidth  = imgFile.width;
  77.  
  78.     // Set our initial background offset
  79.     var horizOffset = 0;
  80.     var vertOffset = 0;
  81.  
  82.     // Get our background var as the document body
  83.     var bgObject = eval('document.body');
  84.  
  85.     // Kick off the scrolling. The second field is delay between updates in milliseconds.
  86.     var ScrollTimer = window.setInterval("scrollBackground(" + imgWidth + "," + imgHeight + ")", updateDelay);
  87.  
  88. // End of JavaScript--> 
  89. </script>
  90.  
  91. </body>
  92.  
  93. </html>

You can see it in action here. WoW! LoL! =P

Yeah… Gonna go with Flash CS4, methinks. But still, bit ‘o fun & all that…

P.S. If the background image doesn’t scroll, try re-loading the page… Not sure why but sometimes it just won’t go without having to do that… Very odd =/

7 thoughts on “How To: Scroll a Web-Page Background using JavaScript”

    1. Hi Michelle,

      I’ve modified the above code so that you can enter values for the horizontal and vertical speeds and change the update delay to whatever values you wish.

      One thing to note is that putting lower movement values and updating more often will increase the smoothness of the scrolling, but at the expense of higher CPU usage (because the update function must be called more often).

      For example:
      – Moving with a horizSpeed of 10 and a delay of 100ms will move the image 10 * (1000 / 100) = 100 pixels in one second, by making 10 calls to the scrollBackground function [Very choppy! =( ]
      – Moving with a horizSpeed of 1 and a delay of 10ms will move the image 1 * (1000 / 10) = 100 pixels in one second, by making 100 calls to the scrollBackground function [Very high CPU! =( ]

      Both of these examples are extremes, and it’s best to find a middle ground – a good value for updateDelay is to leave it at 50ms, so that’s 20 frames per second – if you need smoother animation maybe try 25ms (40 frames per second), and then adjust the horiz/vert speeds to move the background at a speed you like. If you’re moving it very slowly, then you could try increasing the updateDelay and see how it looks – either way you’re looking to find the best compromise you can between smoothness of animation and CPU usage.

      Best wishes,
      r3dux

    1. Hi Tonya,

      For the image to scroll upwards only just change the horizSpeed value (line 66) to 0 and vertSpeed value (line 67) to a negative value.

      Regards,
      r3dux

  1. Hey, script is working awesomely for me! Is there anyway though for me to set background to only repeat on the x and not y?

  2. THANK YOU! I have tried 2 or three different scripts to do that (in addition to trying to write my own javascript) and this is the one that worked for me the very first time. Thank you. Thank you.

Leave a Reply to r3dux Cancel reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.