How to animate with jQuery: Last Week Tonight edition

There are hundreds of jQuery plugins available for you to integrate into your web pages. Many of these are incredibly useful, very well constructed, and incredibly efficient. I use jQuery plugins frequently in order to get the specific effects that I require, and typically one can get along reasonably well without ever really taking a look under the hood. Just plug and play (to an extent).

However, if you only need a few little effects, and not an entire library, perhaps you don’t need to import the jQuery library at all, since it adds more weight to your site. For simple animations, such as having text resize due to a user event (such as a hover, click, mouseover, etc), writing your own animations with jQuery can be fairly straightforward.

Today I discuss how to do this by stringing multiple animations together within a function in order to create the intro for the show Last Week Tonight with John Oliver. If you have never seen the show, I highly recommend you checking out. It’s intelligent and informative while simultaneously witty and hilarious. Every episode is free on Youtube.

You can find the finished animation and the code in its entirety on my Github.

jQuery — The animate() Method

The structure of the jQuery animate() method looks like this:


You target the css element with the selector, apply the .animate() function to the selector that is targeted, and then define the animation within the brackets. Below is an example where I have targeted the tonight selector from my html, applied a delay of 500ms, and animated it by changing opacity to “1” (fully opaque) and increasing the top-margin to 1.1em over the span of 100 milliseconds:

tonight.delay(500).animate({opacity: ‘1’, marginTop: ‘1.1em’}, 100);

jQuery — The delay() Method

A crucial method I am using to control the execution of these animations is the .delay() method. The .delay() method, as used above, allows you specify the milliseconds to delay when executing the animation.

Since 1 second = 1000 milliseconds, you would write “.delay(1000)” to delay the animation for 1 second.

Last Week Tonight animation

If you take a look at my code, you can see that I decided to wrap all of the animations within one single button function, so that clicking the button executes everything.

This function, like all JavaScript/jQuery code should be, is located within adocument.ready function, which makes sure that no JS/jQuery executes prior to the page being fully loaded:


Last thing you want is to have errors because your JS/jQuery is trying to target elements that haven’t loaded yet! You can remove the button just fine, and the animation will begin once the page loads.

In addition to all this, I’ve given all the elements the appropriate CSS styling in order to make it closely resemble the actual Last Week Tonight styling.

There we have it! A fairly simple jQuery animation!

Links: full code, animation