Fly in Newly Added Content to a Page

Published by Chris Coyier

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.

<section class="main" id="main">
  <div class="module">
     ...
  </div>
  <div class="module">
     ...
  </div>
</section>

<aside class="sidebar" id="sidebar">
  <div class="module">
    ...
  </div>
  <div class="module">
    ...
  </div>
</aside>

New Content Comes In

jQuery style.

$("<div />", {
  class: "module",
  html: newContent // from an Ajax request or something
}).prependTo("#sidebar");

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.

$("<div />", {
  class: "module newly-added",
  html: newContent // from an Ajax request or something
}).prependTo("#sidebar");

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 Free1.

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() {
  $(".module").addClass("old-school");
});

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

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

Demo

On CodePen:


1 Prefix Free doesn't work with filter out-of-the-box right now, but you can make it work. See code example from Lea in here.