Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
38
rated 0 times [  44] [ 6]  / answers: 1 / hits: 20072  / 9 Years ago, wed, august 19, 2015, 12:00:00

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


More From » jquery

 Answers
3

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


[#65366] Monday, August 17, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lidialyrick

Total Points: 737
Total Questions: 104
Total Answers: 89

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
;