2

I'm using a technique from this answer for fading in an appended element with jQuery:

$(html).hide().appendTo("#mycontent").fadeIn(1000);

And trying to apply it to a document fragment:

var docfrag = document.createDocumentFragment(),
    div = document.createElement('div');

div.textContent = 'Fade This In';
docfrag.appendChild(div);

But when I try to fade in the fragment:

$(docfrag).hide().appendTo('#container').fadeIn();

I get this error from jQuery:

Uncaught TypeError: Cannot set property 'cur' of undefined

Does anyone know how to fade in the document fragment?

--

Trying to fade in appended list items? See answer below.

Community
  • 1
  • 1
cantera
  • 24,479
  • 25
  • 95
  • 138

2 Answers2

1

$('docfrag') is a DocumentFragment, which has no hide().

Here is the revised code in jsFiddle: link

Reason:

DocumentFragments are DOM Nodes. They are in memory when created and never part of the main DOM tree. Which means jQuery selector will not return as expected a DOM element.

Blaise
  • 21,314
  • 28
  • 108
  • 169
0

I didn't specify this in my question, but the document fragment I'm appending is a series of list items.

Since the list is already rendered with other items, I didn't have the option of fading in a container div the way Blaise and adeneo do in their fiddles.

Fading in the container <ul> would mean fading in the entire list, including the items already there. And I couldn't add another container for just the new list items without breaking the markup or making it really messy.

My solution is a bit hack-ish but gets the job done. This is for a Backbone.js application, so the code here is simplified (and ugly) to get the basic point across without all the Backbone stuff.

var docfrag = document.createDocumentFragment(),
    item1 = document.createElement('li'),
    item2 = document.createElement('li');

item1.textContent = 'New List Item 1';
item2.textContent = 'New List Item 2';

docfrag.appendChild(item1);
docfrag.appendChild(item2);

$item1 = $(item1);
$item2 = $(item2);

$item1.addClass('hidden').hide();
$item2.addClass('hidden').hide();

$('#button').on('click', function() {
    $(docfrag).appendTo('#list');
    $('#list').find('.hidden').fadeIn();
});

Once the new list items are accessible to jQuery (in my case, after running render() on their Backbone views), I hide them and add a class hook for fading them in later.

cantera
  • 24,479
  • 25
  • 95
  • 138