how to prevent default on keypress for certain event but then bring back the default again

Suzi Larsen picture Suzi Larsen · Aug 19, 2015 · Viewed 13.1k times · Source

I have been working on something that requires me to use the space bar to trigger an event. The thing I've been working on is much more complex but i've simplified it down to basics as an example of what I needed to do.

The idea is that when the space bar is held down it highlights this div and when it is let go it un-highlights. I had a problem that when I was pressing down space, the default was to make the scrollbar jump down in stages. To deal with this I tried adding prevent default and then ended up using return false.

This was great...until I realised that when I was testing typing into input field text boxes I had taken away my ability to put a space whilst typing.

What I think I need is either:

  • To (undo) the prevent default or return false somehow after I've finished using it although I couldn't figure out how to do this because I needed this function to be available on the whole page.
  • Stop the spacebar from making the page scroll down when held but still keep it's ability to add spaces when typing text.

Really not sure how to do this.

Here is the code I am using for this example:

HTML

<div class="container">
    <div class="moo">I am moo</div>
    <input/>
</div>

CSS:

.container {
     height:9000px;   
}
.moo {
    border:1px solid black
}
.red {
    background:red;
}
input {
    margin-top:30px;
}

SCRIPT:

$(document).keydown(function(e) {
    if(e.keyCode === 32) {
        $('.moo').addClass('red');
        //event.preventDefault();
        //event.stopPropagation();
        return false;
    }
    else {
        $('.moo').removeClass('moo');
    }
});
$(document).keyup(function(e) {
    if(e.keyCode === 32) {
        $('.moo').removeClass('red');
        event.stopPropagation();
    }
});

DEMO HERE

Answer

Guruprasad J Rao picture Guruprasad J Rao · Aug 19, 2015

DEMO

Capture keypress event instead and toggleClass red and you can check whether the target item is body or input element using e.target.nodeName

$(document).keypress(function(e) {
    if(e.keyCode === 32 && e.target.nodeName=='BODY') {
        $('.moo').toggleClass('red');
        event.preventDefault(); //prevent default if it is body
    }
});

Or if you want to keep the blink on keyup and keydown just keep both the events as below:

$(document).keydown(function(e) {
    if(e.keyCode === 32 && e.target.nodeName=='BODY') {
        $('.moo').toggleClass('red');
        event.preventDefault();
    }
});
$(document).keyup(function(e) {
    if(e.keyCode === 32 && e.target.nodeName=='BODY') {
        $('.moo').toggleClass('red');
        event.preventDefault();
    }
});

DEMO