Closed maureenv closed 8 years ago
Goooood question! I'd recommend creating a custom data-
attribute and storing the data there. For example:
<div id="mycard" data-deck-position="32"></div>
document.getElementById("mycard").setAttribute("data-deck-position", 32);
We haven't really talked about custom attributes much, but they can be really useful. They don't need to start with data-
either -- deck-position="32"
would work fine -- the only difference is with data-
your HTML will validate, and without it the data won't.
Angular.js is built on this whole concept!
I'm sorry, I'm really confused by how to use the data attribute to store the data of a clicked value in the eventListener. Do I need to create a data-deck-position for every card value? I have 16 cards in my array, so am I supposed to create something like:
<div id=mycard" data-deck-position="16"></div>
And how will I connect this attribute div to my array?
I was thinking something like this:
var deck = ["a", "b", "c", "d"];
for(var index = 0; index < deck.length; index++){
// Creates a new div
var div = document.createElement("div");
// Sets the custom attribute with the value of the index
div.setAttribute("data-deck-position", index);
// Stick the div onto the body
document.body.appendChild(div);
// Adds a click listener
div.addEventListener("click", function(){
// `this` is the element that was clicked on. Gets the index from the attribute
var cardIndex = this.getAttribute("data-deck-position");
// Logs the card at that index
console.log(deck[cardIndex]);
});
}
Thanks Robert, this makes more sense now. I will try this out and see if it works
also, would the data-deck-position be equal to the number of cards I have? So if I have 16 cards would it be data-deck-position =16 instead of 32?
<div id="mycard" data-deck-position="16"></div>
Try it! See what happens. :smiley:
I managed to create a deck that shuffles and appears on the board in my memory game. If I click on the card, it will reveal the letter on the back of that card. Now, I want to find a way to return the array value of the card I clicked on. Is there a way to return the array value of the card that is clicked on through the event listener that reveals the card value (on a click) on line 43 in my code?
My repo link is http://maureenv.github.io/project1/