Background Animation

Exclusive offer: get 50% off this eBook here
jQuery 2.0 Animation Techniques: Beginner's Guide

jQuery 2.0 Animation Techniques: Beginner's Guide — Save 50%

Bring your websites to life with animations using jQuery with this book and ebook

$29.99    $15.00
by Adam Culpepper | December 2013 | Beginner's Guides Open Source

In this article by Adam Culpepper, the author of the book jQuery 2.0 Animation Techniques Beginners Guide, has given a detailed description on how to use the animate() effect to animate the background color and learn how to animate the position of background images inside our elements.

(For more resources related to this topic, see here.)

Background-color animation

Animating the background color of an element is a great way to draw our user's eyes to the object we want them to see. Another use for animating the background color of an element is to show that something has happened to the element. It's typically used in this way if the state of the object changes (added, moved, deleted, and so on), or if it requires attention to fix a problem.

Due to the lack of support in jQuery 2.0 for animating background-color, we'll be using jQuery UI to give us the functionality we need to create this effect.

Introducing the animate method

The animate() method is one of the most useful methods jQuery has to offer in its bag of tricks in the animation realm. With it, we’re able to do things like, move an element across the page or alter and animating the properties of colors, backgrounds, text, fonts, the box model, position, display, lists, tables, generated content, and so on.

Time for action – animating the body background-color

Following the steps below, we're going to start by creating an example that changes the body background color.

  1. Start by creating a new file (using our template) called background-color.html and save it in our jquery-animation folder.
  2. Next, we'll need to include the jQuery UI library by adding this line directly under our jQuery library by adding this line:

    <script src = "js/jquery-ui.min.js"></script>

    A custom or stable build of jQuery UI can be downloaded from http://jqueryui.com, or you can link to the library using one of the three Content Delivery Networks (CDN) below. For fastest access to the library, go to http://jqueryui.com, scroll to the very bottom and look for the Quick Access section. Using the jQuery UI library JS file there will work just fine for our needs for the examples in this article.

    Media Template: http://code.jquery.com

    Google: http://developers.google.com/speed/libraries/devguide#jquery-ui

    Microsoft: http://asp.net/ajaxlibrary/cdn.ashx#jQuery_Releases_on_the_CDN_0

    CDNJS: http://cdnjs.com/libraries/jquery

  3. Then, we'll add the following jQuery code to the anonymous function:

    var speed = 1500; $( "body").animate({ backgroundColor: "#D68A85" },speed); $( "body").animate({ backgroundColor: "#E7912D" },speed); $( "body").animate({ backgroundColor: "#CECC33" },speed); $( "body").animate({ backgroundColor: "#6FCD94" },speed); $( "body").animate({ backgroundColor: "#3AB6F1" },speed); $( "body").animate({ backgroundColor: "#8684D8" },speed); $( "body").animate({ backgroundColor: "#DD67AE" },speed);

What just happened?

First we added in the jQuery UI library to our page. This was needed because of the lack of support for animating the background color in the current version of jQuery. Next, we added in the code that will animate our background. We then set the speed variable to 1500 (milliseconds) so that we can control the duration of our animation. Lastly, using the animate() method, we set the background color of the body element and set duration to the variable we set above named speed. We duplicated the same line several times, changing only the hexadecimal value of the background color.

The following screenshot is an illustration of colors the entire body background color animates through:

Chaining together jQuery methods

It's important to note that jQuery methods (animate() in this case) can be chained together. Our code mentioned previously would look like the following if we chained the animate() methods together:

$("body")   .animate({ backgroundColor: "#D68A85"}, speed)  //red   .animate({ backgroundColor: "#E7912D"}, speed)  //orange   .animate({ backgroundColor: "#CECC33"}, speed)  //yellow   .animate({ backgroundColor: "#6FCD94"}, speed)  //green   .animate({ backgroundColor: "#3AB6F1"}, speed)  //blue   .animate({ backgroundColor: "#8684D8"}, speed)  //purple   .animate({ backgroundColor: "#DD67AE"}, speed); //pink

Here's another example of chaining methods together:

(selector).animate(properties).animate(properties).animate(properties)

Have a go hero – extending our script with a loop

In this example we used the animate() method and with some help from jQuery UI, we were able to animate the body background color of our page. Have a go at extending the script to use a loop, so that the colors continually animate without stopping once the script gets to the end of the function.

Pop quiz – chaining with the animate() method

Q1. Which code will properly animate our body background color from red to blue using chaining?

  1. $("body")   .animate({ background: "red"}, "fast")   .animate({ background: "blue"}, "fast");

  2. $("body")   .animate({ background-color: "red"}, "slow")   .animate({ background-color: "blue"}, "slow");

  3. $("body")   .animate({ backgroundColor:"red" })   .animate({ backgroundColor:"blue" });

  4. $("body")   .animate({ backgroundColor,"red" }, "slow")   .animate({ backgroundColor,"blue" }, "slow");

jQuery 2.0 Animation Techniques: Beginner's Guide Bring your websites to life with animations using jQuery with this book and ebook
Published: December 2013
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

The illusion of depth with parallax

The term parallax, when used in the context of computer graphics, especially in video games, refers to the technique of using multiple background layers that scroll at slightly different speeds to create the illusion of depth. Although not as widely deployed in modern gaming, thanks to the advent of richer 3D graphics engines, parallax is still seen frequently in portable gaming devices, and increasingly, on the Web.

A parallax effect is achievable using pure CSS, as demonstrated nicely on the Silverback site (see http://silverbackapp.com for the effect, and http://blog.teamtreehouse.com/how-to-recreate-silverbacks-parallax-effect for the details on how it was implemented). This application of parallax will only become apparent when the window is resized horizontally. While this is a fantastic effect when the window is resized, it doesn't help us if we want the effect to take more of a center stage.

Time for action - creating the stage and adding the styling

The underlying page requires just four elements (for this simple example), which sit in the <body> of the page.

  1. Add the elements in the following structureto a fresh copy of the template file, between the <body> tag, and the first <script> tag:

    <div id="background"></div> <div id="midground"></div> <div id="foreground"></div> <div id="ground"></div>

  2. Save this page as parallax-horizontal.html in our jquery-animation folder.
  3. The CSS in this example is equally as simple as the underlying HTML. Add the following code to a new file in your text editor:

    div {   width:100%;   height:1000px;   position:absolute;   left:0;   top:0; } #background { background:(../images/background.png)repeat-x 0 0; } #midground{ background:(../images/midground.png)repeat-x 0 0; } #foreground { background:(../images/foreground.png)repeat-x 0 0; } #stage { background:(../images/ground.png) repeat-x 0 100%; }

  4. Save this file as parallax- horizontal.css in the css directory and update the HTML file we just created to link to this file.
  5. At this point the page should look like the following screenshot:

The front area is the ground, the foreground layer is the darker colored bushes, the midground is the lighter colored bushes, and the background slice is the sky and clouds.

What just happened?

We have a separate image for each element that we wish to be part of the parallax effect, three in this example, one for the background, one for the midground, and one for the foreground.

The underlying HTML is also very simple. We just have a separate <div> for each layer of the background. In CSS, each image layer is positioned absolutely so that they overlay each other. Now let's get the layers of the parallax moving!

Time for action - animating the background position

Now for the <script> itself. At the bottom of the HTML file, in the empty anonymous function as usual, add the following code:

var bg = $("#background"); var mg = $("#midground"); var fg = $("#foreground"); $(document).keydown(function(e) {   if (e.which === 39) { //right arrow key     bg.animate({ backgroundPosition: "-=1px" }, 0, "linear" );     mg.animate({ backgroundPosition: "-=10px" }, 0, "linear" );     fg.animate({ backgroundPosition: "-=20px" }, 0, "linear" );   } });

If we run this page in a browser now, we should find that as we hold down the right arrow key, the different background image slices move at relatively slower speeds with the foreground almost rushing past, and the background moving leisurely along.

What just happened?

In the script we first cache the selectors we'll be using so that we don't have to create a new jQuery object and select the elements from the DOM each time the background-position changes, which will be very frequently indeed. We then set a keydown event listener on the document object. Within the anonymous function we use as the event handler, we check whether the key code supplied by the which property of the event object (this is normalized by jQuery so it will be accessible cross-browser) is equal to 39, which is the key code returned by the right arrow key.

We then call the animate() on backgroundPosition and we supplied relative values of -=1px, -=10px, and -=20px to move each layer at progressively faster speeds which gives us the parallax effect. These animations are called simultaneously, have their durations set to zero (0) milliseconds, and linear easing. This is the last thing our keydown handler needs to do.

Have a go hero - extending parallax

In this example the backgrounds animate only from right to left. Extend the example so that both the left to right and right to left motion is available. Need help getting started? You'll need to create another function for the left arrow key and increment the backgroundPostion values instead of decrementing like we did in our example.

jQuery 2.0 Animation Techniques: Beginner's Guide Bring your websites to life with animations using jQuery with this book and ebook
Published: December 2013
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

Automatic background animation

In this example, we're going to make the background image animate up the page auto-magically without any special interaction from our user.

Time for action – creating an automatic background animation

We're going to create an example that will automatically animate the background image now.

  1. Create a new file using our template called background-auto.html and save it in our jquery-animation directory.
  2. Since we only have one line of CSS for our example, we aren't going to create a stylesheet. We're going to drop it in the file we just created (background-auto.html) under the <title> tag.

    <style> body {background:  (images/background.jpg) top center fixed;} </style>

  3. Next we'll remove the stylesheet <link> since we won't be using it in this example. This will be the line directly after the code we just added.
  4. Lastly, add the following code into our waiting anonymous function:

    var yPos = 0; var timer = setInterval(start, 50); function start() {     yPos = yPos - 5;     $('body').css({ backgroundPosition: '50% ' + yPos + 'px'       }); }

The following is a screenshot of what we just created. You'll notice that when viewing the example, the background image animates up the back from the bottom to the top.

What just happened?

The first thing we did was declare our variable yPos as an integer. Doing this, as you may know, scares off any spooky JavaScript errors that haunt Internet Explorer and similarly non-modern browser versions.

Next, we declared our timer variable using setInterval().Our function name is start, so we set the function parameter to that. We also set our duration to 50 (milliseconds) as this is a suitable time frame for our function to wait before executing again.

Then we created a function that can be called by our timer named start. We took the current value of yPos and subtract it by five each time our function executes. The last line of our function is what does all the heavy lifting. This line animates the <body> background image's position vertically five pixels each time the function comes to this line in our script.

Have a go hero – playing under the hood

Have a go at changing the timer duration and yPos offset values to see how these values affect the speed and frame rate at which our background animates. Another challenge then would beThen try to make the background animate horizontally instead of vertically like we did for this example.

Let's make it diagonal!

Now, instead of making the background image animate vertically, we're going to animate it diagonally now. Hold on to your programming hats!

Time for Action  animating the background diagonally

We're going to make out animation move diagonally now.

  1. Let's use the same file as before (background-auto.html) and replace the code in our anonymous function with the code below (new code is highlighted):

    var xPos = 0; var yPos = 0; var timer = setInterval(start, 50); function start() {     xPos = xPos - 5;     yPos= yPos - 5; $('body').css({ backgroundPosition:xPos + 'px '+  yPos + 'px' }); }

  2. Save this file as background-auto-diagonal.html and view it in your web browser

    Previewing the animation should look like this:

What just happened?

Using the same code, we gave it a bit of an upgrade to allow us to animate both the X coordinates in addition to the Y coordinates of the background position. The variable xPos was added to control the left and right horizontal position and also added to the backgroundPostion line as well.

Have a go hero

In our example mentioned previously, we made the background image animate northwest. Have a go at making the background animation move Northeast, Southeast, and Southwest. Also, try using the valuesdifferent offset values for the xPos and yPos offsets that aren't the same to see how it affects the background image animation direction.

Parallax background on page elements

Our next example will show you how to animate an element's background position based on the interaction of the window's scroll. This animation can be hard to see based on how smooth scrolling looks in your browser and how smooth the scroll wheel on your mouse is. If you aren't seeing a smooth scroll effect, just grab the scroll bar on your browser and slowly move it up and down to see the effect more clearly. You'll notice that the background position moves at a slower rate than the elements on the page.

Time for action - Setting up the markup and styling

To begin, we'll need to add the necessary HTML and CSS to a new document.

  1. Create a new HTML page using the same template as before and insert the following code into the <body>:

    <div class="row row1">   <img src = "images/image1.png"> </div> <div class="row row2">   <img src = "images/image2.png"> </div> <div class="row row3">   <img src = "images/image3.png"> </div>

  2. Save the page in the jquery-animation directory as parallax-vertical.html.
  3. Next we should create the stylesheet that we just linked to. In a new file, add the following code:

    html, body {     margin:0;     padding:0; } img {     display:block;     width:1000px;     margin:0 auto;     padding-top:200px; } .row { height:700px; } .row1 { background:(images/background1.jpg) repeat-x top   center fixed;} .row2 { background:(images/background2.jpg) repeat-x top   center fixed;} .row3 { background:(images/background3.jpg) repeat-x top   center fixed;}

  4. Save this file as parallax-vertical.css in the css folder within our project folder.

What just happened?

First we added in our HTML structure for the example. This consists of three rows holding only one image each. The CSS is pretty straight forward as well. We're first removing all the space around the html and body elements. Then we set the width and position of the images. We then set the height of the rows, to give us a little space to be able to see the effect. In the wild, this will generally be spaced out by the element's content. Lastly, we set a background image on each of the rows, so that we can see a little variety in our example.

Time for action - scripting our parallax script

Now let's add in the code that'll make our background animate when we scroll down the page.

  1. Add the following code to our anonymous function so we can get this script off the ground and running:

    $(window).scroll(function() {     var yPos = -($(window).scrollTop() / 2);     $('.row').css({ backgroundPosition: '50% '+ yPos + 'px' }); });

Here's a screenshot illustration of how our script will function when previewed in the browser:

What just happened?

We used a window scroll function here because we want to trigger our code every time our user scrolls the window, using the mouse wheel or the browser's scroll bar.

Our variable yPos is set to a negative value because we want the background animation to move in the same direction as the page elements that are being scrolled. Using scrollTop() gives us the current vertical scrollbar position of window. We then divide that number by two.

We use the css() method to set our background position. The value 50% is for the x axis, which is the horizontal axis of our browser. This tells our background image to center itself vertically. The y axis (or yPos in this case) is set to our above variable yPos and then px is appended to tell the script this number is in pixels. The yPos controls the horizontal placement of the image, and therefore centers the background image horizontally.

Have a go hero – customizing the speed and direction of the effect

Try changing the value of the number yPos is divided by, and then try changing the negative number to a positive number. Changing these values affect the speed and direction that our background position scrolls.

Pop quiz – the scroll() and scrollTop() methods

Q1. What does the scroll() method do?

  1. Scrolls to the next sibling element in the set
  2. Allows you to smoothly scroll to an element or numerical value (in pixels) on the page
  3. Allows code to be run each time the selected element is scrolled
  4. When set to false, enables disabled scrolling on the page

Q2. What does the scrollTop() method do?

  1. Jumps back to the top of the page
  2. Outputs the current scroll position of the selected element
  3. When used with the click() method, allows you to scroll to the top of an element
  4. Animates the selected element to roll up like a piece of paper

Summary

In this article, we looked at several examples that animate the background image on an element. Some of the things we learned were:

  • The animate() method and some of the great things we can achieve with it
  • Using jQuery UI to give our script color animation support
  • Fading between background colors on elements
  • Chaining jQuery methods together
  • Parallax animations, where the background layers are animated at different speeds and directions to create the illusion of depth
  • Creating an automatic background image animation and how to make them animate in different directions
  • The scroll() and scrollTop() methods

Resources for Article:


Further resources on this subject:


About the Author :


Adam Culpepper

Adam Culpepper is a frontend web developer who works for Envoc, a software development firm, located in Baton Rouge, Louisiana. He is very active in his community; organizing, founding, and sitting on the board of many industry-related groups and organizations in his area. When he's not reading, writing, working, organizing, or attending a community event, he's spending time with his great friends and family or his girlfriend Amber, his son Aiden and his cat Emma. Adam can be reached at his website (www.adamculpepper.net) or through Twitter (@adamculpepper).

Books From Packt


jQuery UI 1.8: The User Interface Library for jQuery
jQuery UI 1.8: The User Interface Library for jQuery

jQuery Game Development Essentials
jQuery Game Development Essentials

jQuery 1.4 Animation Techniques: Beginners Guide
jQuery 1.4 Animation Techniques: Beginners Guide

jQuery 1.4 Reference Guide
jQuery 1.4 Reference Guide

Instant jQuery Boilerplate for Plugins
Instant jQuery Boilerplate for Plugins

jQuery for Designers: Beginner’s Guide
jQuery for Designers: Beginner’s Guide

jQuery UI 1.7: The User Interface Library for jQuery
jQuery UI 1.7: The User Interface Library for jQuery

jQuery UI 1.10: The User Interface Library for jQuery
jQuery UI 1.10: The User Interface Library for jQuery


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
V
U
q
A
5
Z
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software