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


i have been working on requires me use space bar trigger event. thing i've been working on more complex i've simplified down basics example of needed do.

the idea when space bar held down highlights div , when let go un-highlights. had problem when pressing down space, default make scrollbar jump down in stages. deal tried adding prevent default , ended using return false.

this great...until realised when testing typing input field text boxes had taken away ability put space whilst typing.

what think need either:

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

really not sure how this.

here code using example:

html

<div class="container">     <div class="moo">i 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

demo

capture keypress event instead , toggleclass red , can check whether target item 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 body     } }); 

or if want keep blink on keyup , keydown keep both events 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


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -