Search code examples
javascriptjquerymouseoverkeypress

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


Okay so I can detect a mouseover using .on('mouseover')

and I can detect keypresses using

$(document).keypress(function(e) {
        console.log(e.which);
}

but how do I detect which image my mouse is hovering over when I press a certain button?

the idea is to be able to delete an image by pressing d while hovering over it. any ideas ?


Solution

  • 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