Oberyn Oberyn - 7 months ago 23
HTML Question

Is this a browser issue with HTML5 and javascript?

I'm doing html code in Atom IDE, but i don't get the desired result on the browser, however, when i try with the Atom's HTML preview, i can see the result i want to get.

Here are the screenshots of both the browser and the Atom's preview, please take a look on them:

Atom's HTML preview

Firefox

I've also tried to run the code on Chrome and Internet Explorer, and i get the same result.

Here is my code also:

<!DOCTYPE html>
<html>
<head>
<meta name="author" content="Carlos Cordova">
<meta charset="utf-8">
<title>Assessment 3 part 4 (Finishing the Game)</title>
<style>

img{
position: absolute;
}

div{
position: absolute;
width: 500px;
height: 500px;
}

#rightSide{
left: 500px;
border-left: 1px solid black;
}

</style>

<script>
var numberOfFaces = 5;

function generateFaces(){
for (var i = 0; i < numberOfFaces; i++) {
var newImage = document.createElement("img");
newImage.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
newImage.style.top = Math.floor(Math.random()*400);
newImage.style.left = Math.floor(Math.random()*400);
theLeftSide = document.getElementById("leftSide");
theLeftSide.appendChild(newImage);

theRightSide = document.getElementById("rightSide");
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
theRightSide.appendChild(leftSideImages);


theBody = document.getElementsByTagName("body")[0];

theLeftSide = document.getElementById("leftSide");

theLeftSide.lastChild.onclick = function nextLevel(event){
event.stopPropagation();
numberOfFaces += 5;
deleteAllChildren();
generateFaces();
};

theBody.onclick = function gameOver(){
alert("Sorry, your game is over!");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
};

function deleteAllChildren(){
theLeftSide = document.getElementById("leftSide");
while(theLeftSide.firstChild){
theLeftSide.removeChild(theLeftSide.firstChild);
}
theRightSide = document.getElementById("rightSide");
while(theRightSide.firstChild){
theRightSide.removeChild(theRightSide.firstChild);
}
}
}
/*console.log(theLeftSide.childNodes[0]);
console.log(theLeftSide.childNodes[1]);
console.log(theLeftSide.childNodes[2]);
console.log(theLeftSide.childNodes[3]);
console.log(theLeftSide.childNodes[4]);
*/
}
</script>

</head>
<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>
</body>
</html>


I will be very grateful to help me solve my problem.

Answer

The style attribute needs to be a string. Example:

newImage.style.top = Math.floor(Math.random()*400)+"px";
newImage.style.left = Math.floor(Math.random()*400)+"px";

On the other side, you're setting the same id for different HTML elements. This will result in in very unexpected behavior. If you need to reuse markers then make use of classes instead.