Question

Is there any way that I can access an element that currently has mouse hovered over it using jquery?

I know that I can access an element by attaching mouseover event to an element, but how about when I haven't applied any event to an element and want to access that specific element which is being hovered over by the mouse from any where in the document?

Was it helpful?

Solution

You can attach the mouseover event to the document and get the current element being hovered by using event.target.

Try,

$(document).mouseover(function(e){
  console.log($(e.target).attr('id')); // i just retrieved the id for a demo
});

OTHER TIPS

document.onmousemove = function (e) {
    e = e || window.event;
    evt = e;
}

use evt.target to get the element

The target-attribute of the event object could help you out. For instance:

$('button:first').mouseover(function(e){


   var target = (e.target) ? e.target: e.srcElement;
   console.log(target );// get element that is being hovered over right now

});

or

document.querySelectorAll('button')[0].onmouseover = function(e){

   var target = (e.target) ? e.target: e.srcElement;
   console.log(target);// get element that is being hovered over right now

};

When you want to get the element that is registered to the event-dispacher you have to use the currentTarget-attribut instead. Hope this helps a little bit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top