1

I'm trying to create a dice roller game which adds all of the dice throws into a sum total. I want to be able to have multiple dice rollers open at the same time.

My problem is that ALL the dice are being added together, instead of each separate roller counting its own dice.

You'll see what I mean in this fiddle here: https://jsfiddle.net/txdq7upw/9/

I think the problem is in this code here, since it's taking every element called "dice":

function getSumDiceValue() {
var dice = document.getElementsByClassName("dice");
var diceTotal = 0;
for (var i = 0; i < dice.length; i++) {
  diceTotal += Number(dice[i].getAttribute("data-diceValue"));
};

return diceTotal;

};

My guess is that I need to somehow associate the dice to their own dice roller, but I don't know how to go about doing that.

I'm very new to JavaScript, if it's not too much to ask I'd love some code examples if possible.

Max Zuber
  • 1,217
  • 10
  • 16
Aesthetic Cookie
  • 49
  • 1
  • 1
  • 8
  • I could write pseudo-code for this easily in jQuery, but it doesn't look like you're using it. What you'll need to do is however you're calling that getSumDiceValue function, pass in the dicewrapper that you want to sum up, and inside the function, instead of getting all elements of class dice, get all children of THIS dicewrapper of class dice. So you'd change the function to function getSumDiceValue(wrapper) { ...etc and whenever you call it, pass that in. Hope this helps! – Caleb O'Leary Apr 18 '16 at 15:30

1 Answers1

0

You're done all the job. Just use diceWindowWrapper variable in getSumDiceValue() instead of document to count dices sum in certain closure:

function getSumDiceValue() {
  var dice = diceWindowWrapper.getElementsByClassName("dice");
  // ...
}

You may read more about JavaScript closures in the article How do JavaScript closures work?

Community
  • 1
  • 1
Max Zuber
  • 1,217
  • 10
  • 16
  • Great, worked like a charm. So close yet so far away :) The solution got me thinking and I ended up fixing another problem i was having! Cheers – Aesthetic Cookie Apr 18 '16 at 16:34