O'Reilly logo

Supercharged JavaScript Graphics by Raffaele Cecco

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Scrolling with JavaScript

Although the CSS scrolling techniques described earlier can give some nice effects, the lack of control is frustrating: the parallax effects work only when the browser window is resized, so there is no guarantee that the user will even see the effect. However, with JavaScript, there are no limitations as to how and when scrolling effects can occur. In this section, we will examine two types of JavaScript scrolling techniques: background image scrolling and the more sophisticated tile-based image scrolling.

Background Image Scrolling

The following section recreates the CSS effect in Figure 3-3, but this time, the movement of the mouse over the page controls the direction and speed of scrolling via JavaScript. As the mouse moves to either the left or right of the page, the scrolling will accelerate in the same direction, slowing to a stop as the mouse moves into the middle of the page, or stopping completely when the mouse leaves the page altogether.

With the CSS scrolling code shown earlier in Example 3-1, the background image positions were specified as a percentage of the browser window size. In Example 3-2, the background image positions are manipulated as pixel positions.

Note

For convenience, jQuery is used in the example code.

Example 3-2. Simple JavaScript scrolling

<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>CSS Parallax</title> <style type="text/css"> body { padding:0px; margin:0px; } .layer ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required