Issue
HTML
<div class="user">
<img id="select" class="rock" src="images/rock-removebg-preview.png" onclick="addImg()">
<img id="select" class="paper" src="images/paper-removebg-preview.png" >
<img id="select" class="scissors" src="images/scissors-removebg-preview.png" >
</div>
<div class="player-box"></div>
Javascript
function addImg() {
rock.removeAttribute('onclick')
const newElement = document.createElement('img');
newElement.src = 'images/rock-removebg-preview.png'
playerBox.appendChild(newElement);
rock.addEventListener('onclick', addImg)
}
I am trying trying to create a function where when the image is clicked that respective image gets displayed in the player-box div. I tried a few different variation of javascript programs and none of them are working the way I want it to. Any help would be appreciated.
Solution
Only create the new image once, if it hasn't been created already. On click, copy the src attribute of the clicked image to the one created inside the playerbox
div.
See how it works by running the snippet and clicking one of the three images...
// this "lazy" getter for playerImg will either return or create the img
function playerImg() {
let playerImg = document.getElementById('playerimg');
if (!playerImg) {
playerImg = document.createElement('img');
playerImg.id = 'playerimg';
document.getElementById('playerbox').appendChild(playerImg);
}
return playerImg;
}
// set the source attribute of the playerImg
function setPlayerImg(src) {
playerImg().setAttribute('src', src);
}
// get the rock, paper, scissors elements with their common class
const imgs = document.getElementsByClassName("myclass");
// for each, add a click handler that calls our src setting function
for (let i = 0; i < imgs.length; i++) {
const el = imgs[i];
el.addEventListener('click', () => setPlayerImg(el.src), false);
}
<div class="user">
<img class="rock myclass" src="https://dummyimage.com/100x100/0f0/000" />
<img class="paper myclass" src="https://dummyimage.com/100x100/ff0/000" />
<img class="scissors myclass" src="https://dummyimage.com/100x100/0ff/000" />
</div>
<div id="playerbox"></div>
Answered By - danh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.