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
source share