jnoweb jnoweb - 17 days ago 6
Javascript Question

How can I target three IDs with the same function?

I'm trying to apply the same function to three different IDs. I've created a fiddle to illustrate this: https://jsfiddle.net/jnoweb/xrpsshcp/

var game = {score:0},
scoreDisplay = document.getElementById("score1");

function add20() {
TweenLite.to(game, 1, {
score:"+=20",
roundProps:"score",
onUpdate:updateHandler,
ease:Linear.easeNone
});
}

function updateHandler() {
scoreDisplay.innerHTML = game.score;
}

add20();


So I'm trying to animate the black numbers in the same way as the red number. Any ideas?

Thanks!

Answer

Step 1: Make an Array of elements, store it in scoreDisplay like you did with the first element.

scoreDisplay = [
  document.getElementById("score1"),
  document.getElementById("score2"),
  document.getElementById("score3")
];

Step 2: perform your update function for each element, by using Array.prototype.forEach:

function updateHandler() {
   scoreDisplay.forEach(function(display) {
     display.innerHTML = game.score;
   });
}

In your fiddle: https://jsfiddle.net/ku72qy7e/

Comments