I've been trying to code a matching tiles game where when the person interacts with a tile, it reveals the colour. To do this I created an event listener for all the tiles. In the event listener I capture the target element and then attempt to change the image src of the target element when the user clicks on the element.
After logging to the targetSrc to the console, the src appears to be the same after assigning a new src to it with targetSrc = colour. And therefore, the image remains unchanged in the DOM.
document.querySelectorAll('.tiles').forEach(tile => {
tile.addEventListener('mousedown', function(event) {
let targetElement = event.target; //tile clicked on
let targetId = targetElement.id; //tile id eg; 1, 2, 3
let targetSrc = targetElement.src; //tile current colour eg; transparent.jpg
let colour = tiles[targetId].url; //tile hidden colour eg; red.jpg
targetSrc = colour; //change image src
})
})
However, when I tweak the code and instead write targetElement.src = colour, the src changes and it works.
For an example the code below works perfectly
document.querySelectorAll('.tiles').forEach(tile => {
tile.addEventListener('mousedown', function(event) {
let targetElement = event.target; //tile clicked on
let targetId = targetElement.id; //tile id eg; 1, 2, 3
let targetSrc = targetElement.src; //tile current colour eg; transparent.jpg
let colour = tiles[targetId].url; //tile hidden colour eg; red.jpg
targetElement.src = colour; //change image src
})
})
Is there any reason why targetElement.src works but targetSrc doesn't work even though they are the exact same code?
It's not the exact same code.
let targetSrc = targetElement.src; //Here you are "retrieving" the src attribute
targetElement.src = colour; //Here you are "changing" the src attribute