How to determine if the key is on hover?

I would like to show one divonly when the other is divpointing at , and the space bar is . I tried to use properties keyCodeand whichevents, but none of them worked. Although, I could create an example of pressing the CTRL key, and not a space, as you can see here here .

How can I change the code so that it works with a space (or any other key)?

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();
    });
});
+5
source share
2 answers

You can use the fact that 2 handlers bind. One for mouseenter and one for mouseleave. .hover()

.keydown() .unbind() 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


, .hover() , , .keydown() , .

+9

hover , , , reset . , .

, , .

jquery event.which event.hover , , , .

, .

2

, div . , div .

, $('#myElement").bind('hover keydown', function(){});

0

All Articles