0

I currently have a Javascript game where every hour in the game something else happens.

The game is set to start at 12am and I want to make it so that with the click of a button it adds an hour to the time.

My current is as follows

// time-related info 
var gameTime = 0;  // begin logging time, 12 a.m.
document.getElementById("clock").innerHTML = "Time: " + "12 a.m."; // start the clock at midnight 
function updateTime() {
var clock = document.getElementById("clock");
gameTime++;
if (gameTime >= 24) {
    gameTime = 0;
    clock.innerHTML = "Time: 12 a.m."
} else if (gameTime === 12) {
    clock.innerHTML = "Time: " + gameTime + " p.m.";
} else if (gameTime > 12) {
    clock.innerHTML = "Time: " + (gameTime - 12) + " p.m.";
} else {
    clock.innerHTML = "Time: " + gameTime + " a.m.";
}
}
  • What's your specific question? – Felix Kling Jun 03 '16 at 04:02
  • How can I add a button that will take the time up 1 number – Jony Talassazan Jun 03 '16 at 04:04
  • But what's the issue specifically? Creating the button (which would just be `` I guess)? How to bind an event handler? How to add two values in JavaScript? I'm sure you can find solutions to all of these on the internet already. E.g. https://www.google.com/search?q=javascript+bind+event+handler . Split your problem into smaller problems and find solutions for those. – Felix Kling Jun 03 '16 at 04:10
  • Well, I know that would be the html for the button. I am not sure how to implement the javascript to make the onclick increment – Jony Talassazan Jun 03 '16 at 04:12
  • You already seem to have the code to increment the clock. So all you want to know is how to call that function when clicking the button? – Felix Kling Jun 03 '16 at 04:14
  • Found the duplicate via: https://www.google.com/search?client=safari&rls=en&q=javascript+call+function+on+button+click – Felix Kling Jun 03 '16 at 04:17

2 Answers2

2

// time-related info 
var gameTime = 0;  // begin logging time, 12 a.m.
document.getElementById("clock").innerHTML = "Time: " + "12 a.m."; // start the clock at midnight 
function updateTime() {
var clock = document.getElementById("clock");
gameTime++;
if (gameTime >= 24) {
    gameTime = 0;
    clock.innerHTML = "Time: 12 a.m."
} else if (gameTime === 12) {
    clock.innerHTML = "Time: " + gameTime + " p.m.";
} else if (gameTime > 12) {
    clock.innerHTML = "Time: " + (gameTime - 12) + " p.m.";
} else {
    clock.innerHTML = "Time: " + gameTime + " a.m.";
}
}
<button onclick="updateTime()" >click here</button>
<span Id="clock"/>
Paulo Prestes
  • 484
  • 2
  • 8
1

just add

var clock = document.getElementById("clock");
clock.addEventListener('click', updateTime);
warkentien2
  • 969
  • 13
  • 20