Cubetastic Cubetastic - 27 days ago 11
Javascript Question

JS - How to disable spacebar scrolling ONLY, but allow other spacebar functionality?

I have a website which has regular spacebar functionality, not just inside an input box, so I can't make it return false if the target is the body. I just want to stop it from scrolling down the page, but allow the other functionality. Is it possible to do this using vanilla JS? Here is my code:



//Many other functions here
function spacebar() {
window.onkeydown = function(e) {
if ((watch.isOn) && (!done)) {//u can stop it with any key
watch.freeze();//stop the stopwatch
}
else if (e.keyCode == 32) {
if (done) {
watch.start();//start the stopwatch
stage = 1;
}
if (stage === 0) {
stage = 1;
}
}
}

<html>
<body>
<h1 id="timer">0:00.000</h1>
<script src="js/timer.js"></script>
<!--The JS starts and stops this timer.-->
</body>
</html>





So it starts the timer when the spacebar is pressed, and stops it when any key is pressed.

Answer Source

A default behaviour of pressing the spacebar is to scroll. We have the ability to prevent default behaviors using

event.preventDefault();

You are using window.onkeydown, passing the event argument as var e. You know how to recognize keys by keycode, as you have demonstrated. Now then, if the key that is pressed is the spacebar, then prevent the default behaviors (in this case that includes scrolling). You have the option to define your own behavior instead.