Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Javascript object from HTML element

I have 3 "dice" objects created from this custom constructor:

function Dice() {
  this.value = 0;
  this.keep = false;
  this.roll = function() {
    this.value = Math.floor(Math.random()*6)+1;
  };
}

Then, inside function rollOnce(), I have 3 HTML buttons inside a document.getElementById("paragraph1").innerHTML command that will display each dice's value as follows:

function rollOnce() { 
    (...)
    document.getElementById("paragraph1").innerHTML = 
        '<button id="diceOne" class="unkept" onclick="keepDice(this.id)">'+dice1.value+'</button> ' +
        '<button id="diceTwo" class="unkept" onclick="keepDice(this.id)">'+dice2.value+'</button> ' +
        '<button id="diceThree" class="unkept" onclick="keepDice(this.id)">'+dice3.value+'</button> ';
}

Now, function keepDice(diceId) will set attribute class="kept" for each dice/button that has been clicked.

The next thing I want to do is to know which dice variable (dice1, dice2, dice3) has been clicked (in order to keep their value by doing diceN.keep = true;. Because after that there will be another round of the game in which only those dice which are "unkept" will get another diceN.roll() call. But my knowledge is still very limited and I only know how to access (HTML only) elements by using document.getElementsBy(...) (this is the HTML DOM, right? I'm currently learning this at W3Schools).

I have not yet learned about jQuery, AngularJS and all the other cool webdev stuff. So if it is possible to answer using only Javascript it would be much appreciated (even if other libs would make it easier! It's a bonus if there are alternative solutions and I would be happy to learn too!). Is this possible at all?

Thanks in advance,

like image 281
Felipe Cruz Avatar asked Sep 19 '26 08:09

Felipe Cruz


1 Answers

Maybe something like class="kept-'+dice1.keet+'" onclick="keepDice(1)"

then

function keepDice(index){
    dices[index].keep = true;
    turns--;
    if (turns > 0) {
        rollOnce()
    }
}
like image 161
d3l33t Avatar answered Sep 20 '26 21:09

d3l33t



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!