Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 708
TheDavil Avatar asked Aug 07 '13 16:08

TheDavil


People also ask

Is keypress deprecated?

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.

Is mouseover an event?

The mouseover event is fired at an Element when a pointing device (such as a mouse or trackpad) is used to move the cursor onto the element or one of its child elements.

What is mouseover JavaScript?

mouseover is a special event which is related to the JavaScript and occurs whenever the mouse in pointer comes over an element. Each mouseover event occurs because they have some special property attached to the relatedTarget. mouseover property gets complimented with the target element of the mouseout event.

What is keypress event in JavaScript?

keypress : It fires only when a key that produces a character value is pressed down. For example, if you press the key a , this event will fire as the key a produces a character value of 97 . On the other hand, this event will not fire when you press the shift key as it doesn't produce a character value.


1 Answers

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

like image 91
wirey00 Avatar answered Oct 12 '22 10:10

wirey00