Wilson Luniz
Wilson Luniz

Reputation: 479

Javascript: prevent space key scrolling in specify div

I got a textarea inside a div. The textarea taller than div but not vertical scroll-able. Instead, the div vertical scroll-able. However, when I disable the textarea by javascript and blur() all of them, the space keystroke still affect the div as scroll page down. I tried many way to get rid of this but no luck. Here's my code:

#container {
  overflow-y: scroll;
  overflow-x: hidden;
  float: left;
  white-space: nowrap;
  height: 200px;
}
textarea {
  resize: none;
  overflow-y: hidden;
  overflow-x: scroll;
  word-wrap: off;
  height: 1000px;
}
<div id="container">
  <textarea>{...}</textarea>
</div>

The height of textarea is actually automatic adjusted by javascript when number of lines increase. So it's not a static number. Is that any way to prevent the parent div respond to the space key event? Thanks!

Upvotes: 0

Views: 4523

Answers (1)

dlkulp
dlkulp

Reputation: 2264

This should do the trick. Probably more checks here than necessary but I prefer to err on the side of caution.

document.onkeypress = function(e) {
    e = e || window.event;
    var charCode = e.keyCode || e.which;
    if (charCode === 32) {
        e.preventDefault();
        return false;
    }
}

You could also do this with jQuery if that's your thing:

$(window).keypress(function(e) {
    if (e.which == 32)
        return false;
});

In both of these examples you could change document/window to be your element or whatever element you want to disable spacebar on.

Upvotes: 9

Related Questions