Quantcast
Channel: Help! with 2.0 - Twine Forum
Viewing all articles
Browse latest Browse all 1844

Why element appended to DOM is not avaliable immediately after $(content).append(child)?

$
0
0
I'm using Twine 2.0.11 and SugarCube (v1.0.34) bundled with it.
I'm playing with some JavaScript and found something I don't quite understand.
Why element appended to DOM is not avaliable immediately after $(content).append(child)?

(1)
prerender["addSomethingToDom"] = function (content) {

	if (tags().contains("dynamic")) {
                               
        var child = "<div class='game' id='one'></div>";
        var grandchild = "<div class='game2' style='width:20px;height:20px;background:white' id='two'></div>";
        $(content).append(child);
        
        var target;
                
        target = document.getElementById('one');
        //target not defined...
        $(target).append(grandchild);
        
        //but if we wait 10 ms it works
        waitForElement('#one',function(){
            target = document.getElementById('one');
            $(target).append(grandchild);
        });        
    }
}

(Not shown: waitForElement function body, but I think it's irrelevant)

In jQuery I can write, for example:

(2)
$('#main-div').mouseover(function() {

        var child = "<div class='game' id='one'>Dynamic!</div>";
        var grandchild = "<div class='game2' style='width:20px;height:20px;background:red' id='two'></div>";        
        var grandgrandchild = "<div class='game3' style='width:40px;height:20px;background:green' id='three'></div>"; 
        $('#main-div').append(child);        
        var target;        
 
        target = document.getElementById('one');
        $(target).append(grandchild);
        target = document.getElementById('two');
        $(target).append(grandgrandchild);
});

And it works, append after append.

As for my SugarCube example, I've found a workaround by adding a timeout, although I'm not fond of this solution.
I am interested in understading what's a difference between (1) and (2), so I can implement something more elegant.
Anyone care to elucidate me?

PS.
I know I can chain appends i.e. $(content).append(child).append(grandchild); that would solve this particular case.
But my original code is a little different and doing this is not an option.

Viewing all articles
Browse latest Browse all 1844

Trending Articles