How to detect a keypress AND a mouseover at the same time

I'v added a better example with jsFiddle: http://jsfiddle.net/cUCGX/ (Hover over one of the boxes and press enter.)


Give each image an on('mouseover') and set a variable based on that image.

So

var activeImage = null;

myImage.on('mouseover', function() {
  activeImage = 'myImage';
});

myImage2.on('mouseover', function() {
  activeImage = 'myImage2';
});

$(document).keypress(function(e) {
  if (e.which == 'certainKeyPress'  && activeImage) {
    //do something with activeImage
    console.log('The cursor was over image: ' + activeImage + ' when the key was pressed');
  }
});

Maybe also add an onmouseout to each image as well to clear activeImage if you want the key press to only work WHEN being hovered.


You can just toggle a class or data-attribute that shows you which one is currently being hovered

$('img').hover(function(){
   $(this).toggleClass('active'); // if hovered then it has class active
});
$(document).keypress(function(e) {    
    if(e.which == 100){
       $('.active').remove(); // if d is pressed then remove active image
    }
});

FIDDLE


You should use a mousemove event to permanently store the x & y position in a global variable.

Then, in the keypress handler, grab the element at the last-known mouse position with the document.elementFromPoint(x, y) method.

See https://developer.mozilla.org/en-US/docs/Web/API/document.elementFromPoint


I'm going to go ahead and necro this as I was playing around with this and found I liked my quick solution more. It may not be the best, but it worked better for my needs where I needed a namespace type solution in that the handler would be removed when the dom was in a certain state (sortable):

// Create handler for binding keyup/down based on keyCode
// (ctrl in this example) with namespace to change the cursor
var setCursorBindings = function() {
    $(document).on('keydown.sortable', function(event) {
        if (event.keyCode === 17) {
            $('body').css('cursor', 'pointer');
        }
    }).on('keyup.sortable', function(event) {
        if (event.keyCode === 17) {
            $('body').css('cursor', 'inherit');
        }
    });
};

// Create a handler for reverting the cursor 
// and remove the keydown and keyup bindings.
var clearCursorBindings = function() {
    $('body').css('cursor', 'inherit');
    $(document).off('keydown.sortable').off('keyup.sortable');
};

// Use the jQuery hover in/out to set and clear the cursor handlers
$('.myElementSelector').hover(function() {
    setCursorBindings();
}, function() {
    clearCursorBindings();
});

Tested in Chrome v41