<div class="container">
<img src="https://bit.ly/2Q4q14a" />
<img id="duck" src="https://bit.ly/2KQJVKc" alt="duck" />
<div class="scoreContainer">
<div id="score-text">Score</div>
<div id="score-counter">0</div>
</div>
</div>
/*Make any img element responsive*/
img {
max-width: 100%;
}
/*Set a fixed size for width and height and in an absolute position*/
#duck {
margin: 50px;
width: 100px;
height: 100px;
position: absolute;
left: 100px;
top: 100px;
}
/*Style for the Score container*/
.scoreContainer {
background-color: black;
width: 15%;
height: 15%;
color: #ffffff;
top: 5%;
right: 5%;
border: 2px solid greenyellow;
border-radius: 10px;
display: flex;
position: fixed;
flex-direction: column;
align-items: center;
}
#score-text {
font-size: 1.5em;
}
#score-counter {
font-size: 3.1em;
font-weight: bold;
color: #06e515;
}
//Get the target element
const duck = document.querySelector("#duck");
//Add the click event listener
duck.addEventListener("click", () => {
//Dont forget call the functions here
increaseScore();
moveDuck();
});
//Increase score by 1
const increaseScore = () => {
//Get the content of the target element. The current value for score
const score = document.querySelector("#score-counter").innerHTML;
//Get the element to increase the value
const scoreHTML = document.querySelector("#score-counter");
//Cast the score value to Number type
let count = Number(score);
//Set the new score to the target element
scoreHTML.innerHTML = count + 1;
};
//Get a random number
const getRandomNum = (num) => {
return Math.floor(Math.random() * Math.floor(num));
}
//Move the duck randomly
const moveDuck = () => {
const w = window.innerWidth;
const h = window.innerHeight;
duck.style.top = getRandomNum(w) + "px";
duck.style.left = getRandomNum(h) + "px";
};
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.