How to prevent default when you press a key for a specific event, but then return the default value again

I am working on what requires me to use a space to fire an event. What I worked on is a lot harder, but I simplified it to the basics, as an example of what I needed to do.

The idea is that when holding a space, it highlights this div and when it is released, it does not underline. I had a problem that when I pressed the space bar, the default value was to scroll the scroll bars in stages. To handle this, I tried adding a default ban and then ended using return false.

It was great ... until I realized that when I tested text input in text input fields, I removed my ability to put a space during input.

It seems to me that I need:

  • To (cancel) prevent the default or return false somehow after I finished using it, although I could not figure out how to do this because I needed this feature to be available on the whole page.
  • Stop whitespace from scrolling down the page when held, but still retain the ability to add spaces when entering text.

Not sure how to do this.

Here is the code I use 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

+5
source share
3 answers

Demo

Grab the keypress event and toggleClass red , and you can check if the target element 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 blinking on keyup and keydown , just save both 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

+5
source

Here's how I do it:

 $("input").keydown(function(e) { if(e.keyCode === 32) { $(this).val($(this).val()+ " "); } }); 

Here is the JSFiddle daemon

+3
source

Check out e.target , which tells you which DOM element was focused when keydown / keyup events were fired. Do not disable event handling by default if it is of type textarea or input

0
source

All Articles