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:
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();
}
});
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();
}
});