r3dux.org

A number-pimping side project from the valleys in *NEW* upside-down flavour.

  • Home
  • ABOUT
  • OLD SITE
  • SEARCH
  • FEEDBACK

How To: Scroll a Web-Page Background using JavaScript

r3dux | August 19, 2009

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 saw this background scroller.

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

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

No related posts.

Categories
Coding
Tags
Background, Image, JavaScript, Scroll, Scrolling
Comments rss
Comments rss
Trackback
Trackback
Print This Post Print This Post

« Josh Joplin – Must Be You The Pinocchio Paradox »

4 Responses to “How To: Scroll a Web-Page Background using JavaScript”

  1. Michelle says:
    November 5, 2010 at 6:03 am

    Awesome! Is there a way to change the direction using this code? I want the background to scroll horizontally.

    Reply
    • r3dux says:
      November 5, 2010 at 8:23 am

      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

      Reply
  2. Tonya says:
    April 12, 2012 at 6:43 pm

    Love it! Can you please tell me how to make the background image to scroll UPWARD only?

    Reply
    • r3dux says:
      April 12, 2012 at 7:15 pm

      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

      Reply

Leave a Reply

Click here to cancel reply.

Translate

Categories

Archives

Tags

3D ActionScript ActionScript 3.0 Adobe AI Ballarat Bash C++ Class Convert CS4 Effect Error Film Flash GLSL Gnome Hack How-To install Jaunty Java Kinect Linkage Linux Mash-Up Microsoft Motion OpenGL Particle Problem PS3 Remix Retro script Slides Sound Systems Texture Ubuntu Video VirtualBox Wii Windows XBox

Gamercard

OpenR3dux

Misc.

Flattr this

RSS Feed

r3dux twitter feed



“Honest disagreement is often a good sign of progress.”

 - Mahatma Gandhi

rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox