0

I am trying to make a Cookie Clicker game where when I click an image of a cookie, it adds 1 to a score variable. Every time I click on the cookie, it deletes the image. Can anyone explain this to me, and how to fix it?

<!DOCTYPE html>
<html>
<head>
    <title>Cookie Clickers</title>
    <script>
        function myFunction() {
            var score = 0;
            score++;
            document.write(score);
        }

    </script>
</head>
<body>
    <img src="cookie.jpg" id="cookie" onclick="myFunction()">
</body>
</html>

1 Answers1

0

document.write() will overwrite your entire document. So your img element is disappearing when you do document.write(score).

If all you want to do is error-check that your score variable is actually increasing, I would recomend console.log(score). This will print the value of score to the console, which you can find on your browser by right-clicking and choosing "Inspect Element" and then choosing the "Console" tab to see the console. (This works for both Chrome and Firefox, I'm not sure on other browsers).

If you actually want the score to update on the page, I would create an element with an id="score", and then in your myFunction(), I would use element = getElementById("score") and then element.innerHTML = score.

MoMo
  • 499
  • 3
  • 12
  • Okay. So would the element be something like

    ?

    – MurphyTheTurtle Mar 18 '14 at 18:37
  • That works. But you might want to tell the user what the value is, so you could create a simple
    Score: 0
    . This will make it easier to style later as well. And even though most browser's will auto-close your elements (i.e. add the for your

    or to you ), it's good style to include those explicitly

    – MoMo Mar 18 '14 at 18:43
  • Alright. I am pretty new to Javascript, I am sorry for all the questions. But in the myFunction(), does the element in element = getElementById("score") mean the element that you chose to put the id = "score" in? So, if I chose to use the

    element, I would write p = getElementbyId("score")?

    – MurphyTheTurtle Mar 18 '14 at 18:48
  • First, let's teach you to fish. http://www.w3schools.com/js/default.asp. This is a great place to start. Second, to your question, Javascript can access your HTML elements with methods like getElementByID() and can assign them to a variable. So if you create

    in your HTML and then your Javascript says element=getElementByID("score"), element is a Javascript object that represents your

    element in your HTML. This allows you to manipulate your HTML with JS. The rest, I'll let you discover on your own. Good luck!

    – MoMo Mar 18 '14 at 18:52
  • Thank you for your time! You've been a lot of help. :) I'll mark the question as answered. Thanks again. – MurphyTheTurtle Mar 18 '14 at 18:55