Ilja
Ilja

Reputation: 46527

Do not scroll page down when spacebar is clicked?

As you may know some browsers have this default functionality to scroll page down when spacebar is clicked. I usually like this feature, but due to nature of my website I need to get rid of it.

I've been using

      window.onkeydown = function(e) {
          return !(e.keyCode == 32);
      };

which eats all spacebar functionality and gets the job done, however if user is typing in a comment or a search query and they press spacebar no space is added in a text as this functionality has been eaten up.

So is there a way to disable just the scrolling part and leave all other functionality as it is?

Upvotes: 1

Views: 2335

Answers (3)

Andy G
Andy G

Reputation: 19367

Probably need to equalise for IE:

window.onkeydown = function(e) {
    var evt = e || window.event;
    var elem = evt.target || evt.srcElement;
    if(e.keyCode == 32 && elem.nodeName.toUpperCase() === "BODY") {
        evt.preventDefault();
        return false;
    }
};

(untested)

But you would need to attach an event to/within each iframe, using iframeref.contentWindow.

After the page and iframes have loaded you could loop through the frames[] collection.

Upvotes: 0

claustrofob
claustrofob

Reputation: 4984

window.onkeydown = function(e) {
    return !(e.keyCode == 32 && (e.target.type != 'text' && e.target.type != 'textarea'));
};

Upvotes: 2

A. Wolff
A. Wolff

Reputation: 74420

Maybe try this:

window.onkeydown = function(e) {
          if(e.keyCode == 32 && e.target.nodeName.toUpperCase() === "BODY") e.preventDefault();
      };

Upvotes: 2

Related Questions