Reputation: 23
im making a face matching game that one side has more than the other side and you click on the extra to play but the faces are all under one face on one side of the screen.did i miss place the 'face' element? on the browser it says 'Uncaught TypeError: leftSideImages.node is undefined' and '404 not found'
<body onload="generateFaces()">
<h1>
matching game
</h1>
<p>'Click on the extra smiling face on the left.'</p>
<div id="leftSide"></div>
<div id="rightSide"></div>
<script>
let numberOfFaces = 5;
const theLeftSide = document.getElementById("leftSide");
const theRightSide = document.getElementById("rightSide");
function generateFaces(){
for(let i = 0; i < numberOfFaces; i++){
const face = document.createElement('img');
face.src = 'image/smile.png';
let randomTop = Math.floor(Math.random( 1 * 400)+1);
let randomLeft = Math.floor(Math.random( 1 * 400)+ 1);
face.style.top = randomTop;
face.style.left = randomLeft;
theLeftSide.appendChild(face);
}
const leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.node.removeChild(theLeftSide.theRightSide);
leftSideImages.appendChild(theLeftSide.theRightSide(true));
}
</script>
Upvotes: 1
Views: 82
Reputation: 1999
Your almost there, I think this is what you want.
You have accouple issues. The first is your JS error. To fix it I modified your code slightly. First, I split your function into two. generateFacesInDOM
handles adding the dom, while generateFaces
will tell where and how much, ultimately relying on generateFacesInDOM
. I'm also moved the initial function call from the body tag to JS, so all your JS code is in one place.
I updated your random number to pick a random number between 0 and 100 and then set top and left as a %. Then using CSS we can allow them to position be correctly.
let numberOfFaces = 5;
var theLeftSide, theRightSide;
window.onload = () => {
theLeftSide = document.getElementById("leftSide");
theRightSide = document.getElementById("rightSide");
generateFaces();
}
function generateFaces() {
generateFacesInDOM(theLeftSide, numberOfFaces + 1);
generateFacesInDOM(theRightSide, numberOfFaces);
}
function generateFacesInDOM(parent, faces) {
for (let i = 0; i < faces; i++) {
const face = document.createElement('img');
face.src = 'image/smile.png';
//random number between 0 and 100
let randomTop = Math.floor(Math.random() * 100);
let randomLeft = Math.floor(Math.random() * 100);
face.style.top = randomTop + '%';
face.style.left = randomLeft + '%';
parent.appendChild(face);
}
}
.board {
width: 100%;
height: 200px;
/*Use the grid to make the elements appear side
by side rather than above and below*/
display: grid;
grid-template-columns: 50% 50%;
}
#leftSide,
#rightSide {
position: relative;
}
#leftSide img,
#rightSide img {
position: absolute;
}
<h1>matching game</h1>
<p>'Click on the extra smiling face on the left.'</p>
<div class="board">
<div id="leftSide"></div>
<div id="rightSide"></div>
</div>
Upvotes: 1