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>
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.