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
});
سؤال
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?
المحلول
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
});
نصائح أخرى
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.