Tuesday, December 18, 2012

Fly in newly added content to a page

Fly in newly added content to a page

Say that for any reason, a new module of content needs to appear on a page. By simply appending that new module into the DOM it will instantly appear. That might be enough of an "entrance" - or it might be too subtle. I'd think when you add new content to a page, you want people to see it. Animation might be the ticket. It technically slows down the entrance of the new content, but the visual effect will certainly make it more noticeable. Let's write some code to make all new modules added to a page "fly in".

Already Existing Content...

You have a site. Site has modules.


New Content Comes In

jQuery style.

$("<div />", {
  class: "module",
  html: newContent // from an Ajax request or something

Option #1: Give New Modules a Class

If you have the ability, it's probably cleanest to give newly added content a class so you can target it specifically. In this case, we give it the class newly-added.

Fly in CSS

This new class will have an animation tied to it that does the fly in. It will run immediately after being added to the DOM.

.newly-added {
  animation: flyin 1.2s ease forwards;
  opacity: 0;
  transform: scale(2);
  filter: blur(4px);

@keyframes flyin {
   to { 
     filter: blur(0);
     transform: scale(1);
     opacity: 1;

Note: there are no prefixes being used there. All of animation, transform, filter and @keyframes should be prefixed for the best browser support. Consult CSS3 Please for which to use on which. Or, us Sass/Compass and the appropriate mixins. Or, Prefix Free.

Option #2: Target All New Modules Without a Class

It's possible you don't have control over the classes that newly added content has. In that case, you would target all existing content on the page and give them a class to negate the fly in effect.

$(function() {

Then you could only target new modules with a :not selector:

.module:not(.old-school) {
  /* animation stuff */

See the Pen chriscoyier by Chris Coyier (@chriscoyier) on CodePen.

View Demo