Here’s my function.
function duplicate_step_through_highlighted (element_jq, target_jq, char_cb) {
console.log( element_jq);
var contents = element_jq.contents();
for (var i = 0 ; i < contents.length; ++i) {
// if text node, step
if (contents[i].nodeType === 3) {
// insert empty text node
var new_tn = document.createTextNode('');
target_jq.append(new_tn);
// iterate it
var text = contents[i].nodeValue;
for (var j = 0; j < text.length; j++) {
char_cb(text[j],new_tn);
new_tn.nodeValue += text[j];
// *** I want an async delay here ***
}
} else { // type should be 1: element
// target_jq gets a duplicate element inserted, copying attrs
var new_elem = $(contents[i].cloneNode(false)).appendTo(target_jq);
duplicate_step_through_highlighted($(contents[i]),$(new_elem),char_cb);
// then a recursive call is performed on the newly created element as target_jq
// and the existing one as element_jq. char_cb is passed in
}
}
}
What I’m doing is rebuilding an HTML element by reconstructing it one character at a time. There is a good reason for doing this, I want the visual effect of it getting “typed in”.
So right now there are no delays so my element gets duplicated instantly. I have checked that the result is consistent, but it is becoming clear to me that I will probably need to completely re-write the functionality in order for me to be able to put in an asynchronous delay after each character is inserted.
Will I need to re-write it and have a stack to keep track of my position within the elements?
You might want to have a look at my recent answer or this older one (Demo), on how to implement such an effect.
Tip: Don’t clone the elements into new ones, just hide them and make them appear part-for-part.
Also, it might be easier not to deal with jQuery instances at all but native DOM elements. So yes, a rewrite might do 🙂 And I think it does need a stack as well.
Demo at jsfiddle.net
How it works:
addTextfunction adds some character to the current text node, and sets a timeout for itself – animation! In case everything is done, it invokes thecallbackfunction.childStepruns the animation on a childnode, and passes itself as the callback until no children are left – then nvokes thecallbackfunction.animateNoderecursively runs over the node tree and animates the textnodes in thier order.iteratefunction callsanimateNode(after unhinding them) on all input elements, by passing itself as the callback. After all input elements are finished, it invokes the outercallbackwhich is given as the second argument toanimate.