HTML
<div >
<img id="select" src="images/rock-removebg-preview.png" onclick="addImg()">
<img id="select" src="images/paper-removebg-preview.png" >
<img id="select" src="images/scissors-removebg-preview.png" >
</div>
<div ></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.
CodePudding user response:
Details are commented in example below
// Reference the <form>
const RPS = document.forms.RPS
// Register the click event to <form>
RPS.onclick = addIMG;
// Pass the Event Object
function addIMG(e) {
// Reference all form controls
const IO = this.elements;
// The tag that the user cklicked
const clk = e.target;
// Clean #player to make room.
IO.player.replaceChildren();
/*
** Match clicked tag #id to <img>
*/
if (clk.matches('.rps')) {
switch (clk.id) {
case 'rock':
IO.player.insertAdjacentHTML('afterbegin', `<img src='https://www.biography.com/.image/ar_16:9,c_fill,cs_srgb,g_faces:center,q_auto:good,w_1920/MTc5NjIyODM0ODM2ODc0Mzc3/dwayne-the-rock-johnson-gettyimages-1061959920.webp' height='150'>`);
break;
case 'paper':
IO.player.insertAdjacentHTML(
'afterbegin',
`<img src='https://d1csarkz8obe9u.cloudfront.net/posterpreviews/notebook-paper-background-design-template-c114c2ed2104bd8b815cf7fbb2f34f44_screen.jpg?ts=1636989881' height='150'>`);
break;
case 'scissors':
IO.player.insertAdjacentHTML(
'afterbegin',
`<img src='https://smithsverdict.files.wordpress.com/2013/02/johnny-depp-as-edward-scissorhands-1990.jpeg' height='150'>`);
break;
default:
break;
}
}
}
#objects {
display: flex;
justify-content: space-evenly;
}
object {
display: block;
margin: 0 15px;
cursor: pointer;
}
#player {
width: auto;
max-height: 150px;
text-align: center;
}
img {
object-fit: contain;
}
<form id="RPS">
<fieldset id='objects'>
<legend>Pick One</legend>
<object id="rock" >