Issue
So I'm trying to create a rock paper scissors game with UI using html, css and JS and I got stuck on a problem, whenever the user chooses the rock by clicking the rock button, the rock div that contains the image with a fist should start to move on the screen but in my case it doesn't do anything.
The html:
<div class="game-screen-elements">
<h2 class="choice">Make your choice</h2>
<div class="fist-container">
<div class="fist-left"></div>
<div class="fist-right"></div>
</div>
<div class="pick">
<button class="rock" onclick="click()">rock</button>
<button class="paper">paper</button>
<button class="scissor">scissors</button>
</div>
</div>
</div>
The css:
.fist-container{
display: flex;
width: 100%;
justify-content: space-around;
}
.fist-right, .fist-left{
background-image: url(assets/rock.png);
width: 300px;
height: 300px;
background-size: cover;
}
.fist-left{
transform: rotateY(180deg);
}
@keyframes fistLeft {
0% {
transform: rotateY(180deg) translateY(0px);
}
15% {
transform: rotateY(180deg) translateY(-50px);
}
/*25% {
transform: rotateY(180deg) translateY(0px);
} */
35% {
transform: rotateY(180deg) translateY(-50px);
}
50% {
transform: rotateY(180deg) translateY(0px);
}
65% {
transform: rotateY(180deg) translateY(-50px);
}
75% {
transform: rotateY(180deg) translateY(0px);
}
85% {
transform: rotateY(180deg) translateY(-50px);
}
100% {
transform: rotateY(180deg) translateY(0px);
}
}
@keyframes fistRight {
0% {
transform: translateY(0px);
}
15% {
transform: translateY(-50px);
}
/*25% {
transform: translateY(0px);
} */
35% {
transform: translateY(-50px);
}
50% {
transform: translateY(0px);
}
65% {
transform: translateY(-50px);
}
75% {
transform: translateY(0px);
}
85% {
transform: translateY(-50px);
}
100% {
transform: translateY(0px);
}
}
The JS:
const playerHand = document.querySelector('.fist-left');
const rockChoice = document.querySelector('rock');
click = function(){
rockChoice.addEventListener('click', function(){
playerHand.style.animation = 'fistLeft 2s ease';
});
};
Solution
Here is your working Javascript code:
const playerHand = document.querySelector('.fist-left');
const rockChoice = document.querySelector('.rock');
rockChoice.addEventListener('click', click);
function click(){
playerHand.style.animation = 'fistLeft 2s ease';
}
Explanation: What your click function does is simply registering the event-listener and not necessarily executing the animation code, hence the event is not triggered. The separated click function now actually runs the code responsible for animation since it has been registered for any click events on your element with .rock class. Also make sure you are placing the JS code at the bottom of the body tag(inside closing body tag) if you are using it as external script.
Answered By - Dorji Tshering
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.