I would like to show one div only when another div is hovered and the Space Bar is down. I tried to use keyCode and which properties of the event, but none of them worked. Though, I could create an example for CTRL key pressed rather than the Space Bar, as you can see also here.
How should I change the code so it will work with Space Bar (or any other key) down?
HTML:
<div class='a'></div>
<div class='b'></div>
CSS:
body {
position: relative;
}
div {
width: 100px;
height: 100px;
position: absolute;
}
.a {
background: #777;
left: 50px;
top: 30px;
}
.b {
display: none;
background: #000;
left: 250px;
top: 100px;
}
JS:
$(function() {
$('div').hover(function(e) {
if (e.ctrlKey) {
$('.b').show();
}
}, function() {
if ($('.b').is(':visible')) $('.b').hide();
});
});
You can make use of the fact that
.hover()binds 2 handlers. One for mouseenter and one for mouseleave.Bind a
.keydown()on mouseenter and simply.unbind()it on mouseleave:jsFiddle example
An important note is that
.hover()will work even if the window hasn’t been focused, but.keydown()will only work if the window is in focus.