Given the following code, how would I end tileClick() to change clicking the image with "tileBack.jpg" to instead display the image that was assigned to this particular div in shuffleDeck() ? I mean, the tileClick() function should accept the fragment that currently displays the tileBack image, and when clicked, shows the image that is on the "back side" of this fragment.
So far, you can see how I tried to target a specific fragment, but I'm not sure what this. used here correctly. On the other side of this statement, I tried to do things like = "../img/tile_"+tiles[i]+".png"; but, obviously, the problem is that i does not exist within this function. My problem is that I cannot figure out how to restructure my code so that I can access the image that was previously assigned to the given div . For reference, the "other side" of the tiles is called "tile _ ##. Png", where "##" is a 2-digit number (01-12).
I am very new to JS and programming in general, so please keep your answers simple enough so that I can understand and implement them.
var deck = []; var tiles = []; var sources = [ "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" ]; var images = []; const WIDTH = 100; const HEIGHT = 100; const NUMTILES = 24; loadImages(); buildDeck(); shuffleDeck(7); printDeck(); function loadImages() { for (var i = 0; i < sources.length; i++) { images[i] = "../img/tile_"+sources[i]+".png"; } } function buildDeck() { for (var i = 0; i < 2; i++) { for (var j = 0; j < sources.length; j++) { var tempTile = {}; tempTile.val = sources[j]; tempTile.img = images[j]; deck.push(tempTile); } } } function shuffleDeck (numTimes) { for (var i = 0; i < numTimes; i++) { for (var j = 0; j < deck.length; j++) { var tempTile = deck[j]; var randI = j; while ( randI == j ) { randI = Math.floor(Math.random() * deck.length ); } deck[j] = deck[randI]; deck[randI] = tempTile; } } } function printDeck() { for (var i = 0; i < NUMTILES; i++) { tiles[i] = document.getElementById("tile"+i); console.log(deck[i].img); tiles[i].style.backgroundImage = "../img/tileBack.jpg"; } } function tileClick() { document.querySelector(".tile").addEventListener("mousedown", function () { this.style.backgroundImage = }); }
JS Fiddle Link: http://jsfiddle.net/Leor6jqr/
source share