Mammolytic
Mammolytic

Reputation: 155

Javascript arrays randomizing elements up to a selected element

I am trying to make a function where when you click one of the dice elements, it will re-roll that dice, and every element to the left of it re-rolls also.

Currently I have it when you load the page, the dice are numbered 1-6 and when you click a dice, it re-rolls it. I am having a bit trouble trying to figure out how to make all the elements to the left of the selected element change.

Here is what I have.

   (function () {
  var dieElements;

  dieElements = Array.prototype.slice.call(document.querySelectorAll('#dice div'));

  dieElements.forEach(function (dieElement, whichDie) {

     dieElement.textContent = whichDie + 1;

     dieElement.addEventListener('click', function () {
        dieElement.textContent = Math.floor(Math.random() * 6) + 1;
     }, false);
  });
}());

Heres the html

<fieldset id="dice-area">
<legend>Dice</legend>
<div class="box-of-dice" id="dice">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
</fieldset>

Upvotes: 0

Views: 39

Answers (1)

ibrahim mahrir
ibrahim mahrir

Reputation: 31682

You already have the index of the die clicked and the array of all the dice trapped in a closure. All you need is use them (Easily) like this:

(function() {
  var dieElements;

  dieElements = Array.prototype.slice.call(document.querySelectorAll('#dice div'));

  dieElements.forEach(function(dieElement, whichDie) {
    dieElement.textContent = whichDie + 1;

    dieElement.addEventListener('click', function() {                    // when this die is clicked
      for(var i = 0; i <= whichDie; i++)                                 // loop over all the elements in dieElements array from index 0 to index whichDie (included)
        dieElements[i].textContent = Math.floor(Math.random() * 6) + 1;  // change their textContent
    }, false);
  });
}());
#dice div {
  display: inline-block;
  border: 1px solid black;
  padding: 5px;
  margin: 5px;
  width: 30px;
  height: 30px;
  text-align: center;
  cursor: pointer;
}
<div id="dice">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

Upvotes: 2

Related Questions