
Question:
I am finishing an assesstment for a course certificate. In my final task I am asked to create a mini js game that will generate random faces in two mirror sides and one side will have a missing face.<br /> An onclick event above the "<em>missing face</em>" should trigger my function <strong>nextLevel()</strong> that will erase the two divs (mirror divs) and generate new content.<br />
I have develop this script in order to achieve the problem but I have an specific error for the onclick
event. It says:
Uncaught TypeError: Cannot set property 'onclick' of null
</blockquote>But running a DOM viewer it says there is 5 childs added on the leftSide Div. Please, help me I cant find the solution to this issue.
var numberOfFaces=5;
var theLeftSide=document.getElementById("leftSide");
var theRightSide=document.getElementById("rightSide");
var theBody =document.getElementsByTagName("body")[0];
function generateFaces(){
for(i=0;i<numberOfFaces;i++){
var oImg=document.createElement("img"); // Creates an oimg node
oImg.setAttribute('src', 'http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png'); // sets the source for img file
theLeftSide.appendChild(oImg); // append the img to leftSide Div.
oImg.style.top = Math.floor(Math.random()*401)+'px';
oImg.style.left = Math.floor(Math.random()*401)+'px';
}
copyDiv();
}
function copyDiv(){
var cloned = theLeftSide.cloneNode(true);
cloned.removeChild( cloned.childNodes[ cloned.childNodes.length - 1 ] );
theRightSide.appendChild(cloned);
}
theLeftSide.lastChild.onclick=function nextLevel(event){
event.stopPropagation();
numberOfFaces += 5;
deleteAllChilds();
generateFaces();
};
/*
theBody.onclick =function gameOver() {
alert("Game Over!");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
};
*/
function deleteAllChilds(){
while(theLeftSide.childNodes.length>0){
theLeftSide.removeChild(theLeftSide.childNodes[theLeftSide.childNodes.lenth-1]);
}
while(theRightSide.childNodes.length>0){
theRightSide.removeChild(theRightSide.childNodes[theRightSide.childNodes.lenth-1]);
}
}
Answer1:It was the position of the function nextLevel. Adding it inside the function generateFaces will provide the usability I was looking for. Thank you all.
Answer2:generally the
<blockquote>Uncaught TypeError: Cannot set property 'onclick' of null
</blockquote>is warned when you're trying to apply an events on a DOM Object which is not loaded yet !! to avoid this verify that your script is loaded in the <head>
element or if it is in the body be sure that it was loaded before HTML content having as id "leftSide" ..