I have the following code with intention of stoping the handling of mouse clicks on webpage, after the very first mouse click.
// The following is inside the onload function of html BODY.
var theLeftSide = document.getElementById("leftSide");
var theBody = document.getElementsByTagName("body")[0];
theBody.addEventListener("click", function() {
gameOver( theLeftSide, theBody );
});
....................
function gameOver(theLeftSide, theBody){
alert("That is not the correct face. Game over.");
theBody.onclick = null;
theLeftSide.lastChild.onclick = null;
}
But, the mouse handling does not stop (as indicated by the alerts). I did some search, to confirm that javascript passes "object parameters" by reference. When i step through the debugger, i see the event handler (theBody.onclick) is getting set to NULL. Why is this change in gameOver() not affecting the webpage body ?
UPDATE: Thanks to all the comments. Even though i realized my mistake when i took a break after my original post, all replies were helpful to me to learn things that i did not know before, especially since they induced me to read docs further. I had to modify the accepted answer, because the variables were local to a function and not global. So, current code which has solved my trouble looks like this ::
theBody.addEventListener("click", function clickListener() {
gameOver( theLeftSide, theBody, clickListener );
});
And outside the function where the above statement is, i have
function gameOver(theLeftSide_param, theBody_param, clickListener_param) {
alert("That is not the correct face. Game over.");
theBody_param.removeEventListener("click", clickListener_param);
theLeftSide_param.lastChild.onclick = null;
}
clickListener had to be passed as a parameter, because that was not a global and was not visible outside to gameOver().
removeEventListener