-1

I am writing a simple game and want to add a click event to the body element. But the script below does not work. Is there anything I can change to make it work?

var theBody = document.getElementsByTagName("body")[0];
theBody.addEventListener("click", gameOver);
theBody.onclick = gameOver();
function gameOver() {
    alert("Game Over!");
}
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
susansecret
  • 293
  • 1
  • 3
  • 5
  • 5
    `theBody.onclick = gameOver;` - get rid of the `()` because that means that you're *calling* the function. – Pointy Dec 14 '15 at 04:09
  • also `var theBody = document.body;` is a little simpler :) – Pointy Dec 14 '15 at 04:09
  • 1
    `theBody.onclick = gameOver();` is not needed..Try this: https://jsfiddle.net/muevbeqm/ – Rayon Dec 14 '15 at 04:10
  • 1
    @Pointy, I have edited that..What I meant was `theBody.addEventListener("click", gameOver); theBody.onclick = gameOver();` both the lines does the same operation and later one is written inappropriately.. – Rayon Dec 14 '15 at 04:12
  • @Pointy, What is the point of having 2 event listener having same callback on the same element ? – Rayon Dec 14 '15 at 04:15
  • This game seems sad. How do you win? ;) – akosel Dec 14 '15 at 04:15
  • @RayonDabre ah, well that's certainly a good point. I retract my statement because you're 100% correct, and I offer my apologies. – Pointy Dec 14 '15 at 04:15
  • @Pointy, he he.. May be I need to work on framing sentences :P – Rayon Dec 14 '15 at 04:17
  • 2
    Possible duplicate of [JavaScript - onclick event getting called automatically](http://stackoverflow.com/questions/10101899/javascript-onclick-event-getting-called-automatically) – Sebastian Simon Dec 14 '15 at 04:32

2 Answers2

1

Use this:

document.body.addEventListener("click", gameOver);  

Or this:

document.body.onclick = gameOver; // no brackets 

Not both.

Charles Clayton
  • 17,005
  • 11
  • 87
  • 120
  • Thank you. I removed some code and now the code is as below. But it still doesn't work... theBody.addEventListener("click", gameOver); function gameOver() { alert("Game Over!"); } – susansecret Dec 14 '15 at 04:28
-1
Try this:

document.getElementsByTagName("body ").addEventListener("click", function(){
    gameOver();
});
function gameOver() {
    alert("Game Over!");
}
Meenakshi
  • 165
  • 1
  • 8
  • @susansecret [No, this absolutely does not work...](http://jsfiddle.net/5wvb654u/) It throws the error `document.getElementsByTagName(...).addEventListener is not a function` because you can't assign an event listener to an array. It's also terrible style because you're creating a function just to call another function. – Charles Clayton Dec 14 '15 at 06:10