1

I am learning how to develop and I wanted to work on a simple "clicker" game using HTML5, CSS3, and JavaScript. I'm looking to practice creating something similar to Cookie Clicker. I have created three icons and they each serve a purpose. I would like to figure out how to display a modified variable on a portion of the screen without clearing the screen or having to resort to a window popup.

Here is the link to the project if anyone is interested in helping:

https://github.com/HandleThatError/Practice

The function in question is the displayPoints function in the master.js file. I currently have the following:

function displayPoints() {
    confirm(numClicks);
}

This does what I want. It displays the correct number of clicks. If I click on the middle button twenty times and then click the "Display Points" button, it'll display the right number of points. However, it does it in a popup window. How can I display the number of points inside the browser without using a popup window?

I tried the following code:

function displayPoints() {
    document.write(numClicks);
}

This code worked inside the browser but it cleared the screen of the icons, so it's not possible to keep generating points by clicking on the second button.

tl;dr - How can I update variables in real time, on the browser screen, without using a popup window and without clearing the screen? Any help would be much appreciated.

HandleThatError
  • 598
  • 7
  • 29

2 Answers2

4

You can use an html element on the page and fill it with data such as:

<span id="numClicksResult"></span>
<script>document.getElementById('numClicksResult').innerHtml=10;</script>
Amr Elgarhy
  • 66,568
  • 69
  • 184
  • 301
  • When you say html element, do you mean to have a

    somewhere in the HTML file? How would I go about implementing your solution into my code? I'd like to read more about this - perhaps you can recommend a resource for me to read. Thanks so much for your help!
    – HandleThatError May 25 '14 at 21:47
  • 1
    something like this http://www.w3schools.com/js/js_htmldom_html.asp may help – Amr Elgarhy May 26 '14 at 00:22
2

This is an important concept that links HTML and JS:

You need an element to store what you're going to update. This is usually a div.

<div id="myDiv"></div>

Then, in your JS, you need a way of accessing the div.

document.getElementById("myDiv");

This gives you the element, but you need to update the element's value.

document.getElementById("myDiv").innerHTML;

So, you can access the value, but you need to update it whenever there's a click. When the user clicks, you do all of the work you need on your variable and then...

document.getElementById("myDiv").innerHTML = myVar;
AstroCB
  • 12,337
  • 20
  • 57
  • 73