views:

38

answers:

2

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

On hover i'd be setting a flag and then on leaving hover state i'd reset the flag. then when the space bar is pressed you can check whether you are in a hover state.

i'm not sure that hover and space can be trapped in the way you would like.

edit

in jquery you could combine event.which and event.hover on the same element and maybe you could chain them.

i'll take a quick look but i don't like your chances.

edit 2

the issue is that a div won't get any key events. i think you need to attach a key listener to the document and a hover on the div and keep a flag.

you can chain events like this $('#myElement").bind('hover keydown', function(){});

griegs
But why it does work with CTRL key and cannot work with other key ?
Misha Moroshko
I believe it's because the ctrl key isn't a displayable chr and so is trapped by elements and bubbled up. the div has no way to handle a displayable chr and so doesn't bother with it.
griegs
+2  A: 

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:

$(function() {

      // Define the mouseenter and mouseleave handlers with hover
    $("div.a").hover(function() {

          // Show other div if a key is pressed.
          // You can of course check for on particular key.
        $(document).keydown(function() {
            $("div.b").show();
        });

    }, function() {

         // unbind the keydown handler on mouseleave
       $(document).unbind("keydown");

       $("div.b").hide();
    });
});​

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.

Peter Ajtai
Nice solution ! Thanks a lot !
Misha Moroshko
@Misha - You're welcome ;)
Peter Ajtai