How To Become A Programmer Without A Degree & Experience

Stopwatch with JavaScript (2) – Start & Stop with Spacebar –

Did you try “Stopwatch with JavaScript”?
Stopwatch with JavaScript

 

I got a question about how to start and stop the timer with a spacebar.
I think this is a very useful function, so let’s add it!

 

Here is the code.

Please add line3~13 right before </script>.

...
 
    document.onkeydown = function(event) { 
		if (event) {
			if (event.keyCode == 32 || event.which == 32) {
				if(status == 1) {
					stop();
				} else if (status == 0) {
					start();
				}
			}
		} 
	};
 
</script>

 

If you want to use “Enter” instead of “Space”, change 32 to 13.

 

Example (and more)

KeyCode
Space32
Enter13
S83

 

I hope this works well with your stopwatch.
Happy coding 🙂