views:

312

answers:

5

At the moment I'm adding elements to a page on a click event using after. I'd like to animate this in some way so the new elements don't suddenly appear out of nowhere.

I'm not bothered what animation method is used as long as it shows to the user what is happening when they click.

I've never used animation in jQuery before and have only really found examples for working with existing DOM elements. What pattern should be used for animating the creation of new elements in jQuery?

+2  A: 

A simple fadeIn usually works well.

scunliffe
+5  A: 

You could do something like:

...click(function() {
    $(...).hide().appendTo(...).fadeIn();
}
googletorp
+1 for simplicity!
brownstone
+2  A: 

Try something like this:

$("selector").hide().fadeIn(1000);

where 1000 is the speed of which the item can fade in. I put the hide() in there assuming that the new DOM element is visible when created, not sure if it's needed or not. Best thing to do is put a "display: none" on the new element when you create it and then just use fadeIn().

There's other effects you can use too like slideUp/slideDown so you may want to look into those too.

Willson Haw
+2  A: 

You can go for any animation. You can go for a simple show

$("#element").show("slow") // or "normal" or "fast"
// or
$("#element").show(1000) // 1000 milliseconds

Or as previously suggested, fadeIn. Again you can decide the speed - like in show. Or you could go for a custom animation.

$("#element").animate({
    opacity: 1, // Will fade the object in
    fontSize: "14px", // Will animate the font size too
}, 1000); // 1000 milliseconds

Go here for the jQuery effects documentation.

abhinavg
+1  A: 

What I've done in the past is insert zero-size placeholder-divs at the point where I want to insert my new element.

I then animate that placeholder to the size I want, then insert a hidden version of the element I want to show inside the placeholder and fade it into view.

Once the fade-in is complete I 'unwrap' the placeholder to remove it, using the following code:

 // Essentially, this does the opposite of jQuery.wrap. Here is an example:
 //
 //  jQuery('p').wrap('<div></div>');
 //  jQuery('p').parent().unwrap().remove();
 //
 // Note that it is up to you to remove the wrapper-element after its
 // childNodes have been moved up the DOM
 jQuery.fn.unwrap = function () {
  return this.each(function(){
   jQuery(this.childNodes).insertBefore(this);
  });
 };

All jQuery animation features have 'onComplete' handlers that allow you to kick-off different parts of the animation once they're completed, so it's not too much of a chore to achieve all of this.

Also, it's very useful to keep a JavaScript model of all your elements instead of relying on slow DOM-traversal and the jQuery .data() method.

brownstone
I don't know if this was really what I was looking for but it seems so cool I can't help but mark it as the answer.
Alex Angas