Carl Papworth Carl Papworth - 7 months ago 15
Javascript Question

each() only working on last object (with foreach loop)

I'm trying to call a HTML5-Canvas Animation and repeat it in each item with the class

.object
. However javascript only works with last item!

<ul>
<li><canvas class="object"></canvas></li>
<li><canvas class="object"></canvas></li>
<li><canvas class="object"></canvas></li>
<li><canvas class="object"></canvas></li> //this one shows
</ul>


$('.object').each(function(){
var $class = $(this).attr('class').split(' ').pop();
var $library = new lib.Animation();
myAnimation($class, $library);
});

function myAnimation($class, $library) {
var $canvas = document.getElementsByClassName($class);
for (i = 0; i < $canvas.length; i++) {
var $canvas_root = $library;
var $canvas_stage = new createjs.Stage($canvas[i]);
$canvas_stage.addChild($canvas_root);
$canvas_stage.update();
createjs.Ticker.setFPS(24);
createjs.Ticker.addEventListener("tick", $canvas_stage);
}
}


I got it working using ID, however I would prefer to get it working for each item with a class:

<ul>
<li><canvas id="object1" class="object"></canvas></li>
<li><canvas id="object2" class="object"></canvas></li>
<li><canvas id="object3" class="object"></canvas></li>
<li><canvas id="object4" class="object"></canvas></li> //this one shows
</ul>


$('.object').each( function() {
var $id = $(this).attr('id');
var $library = new lib.orbeOther();
myAnimation($id, $library);
});

function myAnimation($id, $library) {
var $canvas = document.getElementById($id);
var $canvas_stage = new createjs.Stage($canvas);

$canvas_stage.addChild($library);
$canvas_stage.update();

createjs.Ticker.setFPS(24);
createjs.Ticker.addEventListener("tick", $canvas_stage);
}
});

Answer

If you already have a reference to the element (as in the each() code block) then there is little point extracting the class of the element to pass to another function to re-select the element; just pass the element.

Also note that your current logic is flawed as you have a loop within a loop. Try this simplified version:

$('.object').each(function() {
    var library = new lib.Animation();
    var $canvas_stage = new createjs.Stage(this);
    $canvas_stage.addChild(library);
    $canvas_stage.update();
    createjs.Ticker.setFPS(24);
    createjs.Ticker.addEventListener("tick", $canvas_stage);
});

Finally you need to fix your HTML as your closing </canvas are missing the >.