Determine Which Element the Mouse Pointer Is on Top of in JavaScript

How to get top,left of the element which mouse went over on it?

with vanilla js you can do something like:

document.getElementById("question-header").addEventListener("mouseover",(e)=>{
const element = e.target.getBoundingClientRect();
const left = element.left;
const top = element.top;
const width = element.width;
const height = element.height;

console.log(`Left: ${left}, Top: ${top}, Width: ${width}, Height: ${height}`);
})

If you need to get all the computed styles, you can do something like:

document.getElementById("question-header").addEventListener("mouseover",(e)=>{
const elementStyles = getComputedStyle(e.target);
console.log(elementStyles);
})

Find mouse position relative to element

For people using JQuery:

Sometimes, when you have nested elements, one of them with the event attached to it, it can be confusing to understand what your browser sees as the parent. Here, you can specify which parent.

You take the mouse position, and then subtract it from the parent element's offset position.

var x = evt.pageX - $('#element').offset().left;
var y = evt.pageY - $('#element').offset().top;

If you're trying to get the mouse position on a page inside a scrolling pane:

var x = (evt.pageX - $('#element').offset().left) + self.frame.scrollLeft();
var y = (evt.pageY - $('#element').offset().top) + self.frame.scrollTop();

Or the position relative to the page:

var x = (evt.pageX - $('#element').offset().left) + $(window).scrollLeft();
var y = (evt.pageY - $('#element').offset().top) + $(window).scrollTop();

Note the following performance optimisation:

var offset = $('#element').offset();
// Then refer to
var x = evt.pageX - offset.left;

In this way, JQuery does not have to look up #element for each line.

Update

There is a newer, JavaScript-only version in an answer by @anytimecoder -- see also browser support for getBoundingClientRect().

Hover the element below the mouse cursor when scrolling

One approach of tackling this is storing the mouse cursor location with the mousemove event and in the scroll event use document.elementFromPoint(x, y) to figure out the element that should be hovered.

Keep in mind that this is still pretty inefficient due to the scroll event being fired with such a high frequency. The event handler should be debounced to limit execution of the function to once per delay. David Walsh explains how to do this in JavaScript Debounce Function.

let hoveredElement;let mouseX = 0, mouseY = 0;
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('mousemove', event => { mouseX = event.clientX; mouseY = event.clientY;
hover(event.target); });
document.addEventListener('scroll', () => { const hoverTarget = document.elementFromPoint(mouseX, mouseY); if (hoverTarget) { hover(hoverTarget); } });});
function hover(targetElement) { // If the target and stored element are the same, return early // because setting it again is unnecessary. if (hoveredElement === targetElement) { return; }
// On first run, `hoveredElement` is undefined. if (hoveredElement) { hoveredElement.classList.remove('hover'); }
hoveredElement = targetElement; hoveredElement.classList.add('hover');}
.element {  height: 200px;  border: 2px solid tomato;}
.element.hover { background-color: lavender;}
<div class="container">  <div class="element element-1">1</div>  <div class="element element-2">2</div>  <div class="element element-3">3</div>  <div class="element element-4">4</div>  <div class="element element-5">5</div></div>

How to check if the cursor is over an element?

I'm not really sure why you wish to avoid hover so badly: consider the following script

$(function(){

$('*').hover(function(){
$(this).data('hover',1); //store in that element that the mouse is over it
},
function(){
$(this).data('hover',0); //store in that element that the mouse is no longer over it
});

window.isHovering = function (selector) {
return $(selector).data('hover')?true:false; //check element for hover property
}
});

Basically the idea is that you use hover to set a flag on the element that the mouse is over it/no longer over it. And then you write a function that checks for that flag.

Get element currently under mouse without using mouse events

I just looked through the source for code that gets (or stores and makes available) the cursor position. I didn't find anything one could use (from Javascript, XPCOM or not). I might have missed something... MXR is your friend.

However, if you want to avoid mousemove (and this is a good idea in general), you can just look for the innermost hovered element, e.g. like so.

function getInnermostHovered() {
var n = document.querySelector(":hover");
var nn;
while (n) {
nn = n;
n = nn.querySelector(":hover");
}
return nn;
}

(fiddle demoing the principle)

While this is what I'd consider a hack, it seems to work good enough most of the time, but will fail if the element has mouse events disabled via pointer-events. There could be other issues I didn't think of...

Of course, this can return nothing when the document has no hovered element (e.g. the mouse is not actually within the document).

Javascript: Know all the elements under your mouse pointer (multiple z-axis layers)

Just look under each element until you reach the html tag. You can hide/show elements or use pointerEvents for this:

http://jsfiddle.net/Gwy2u/

$(window).click(function(e) {
var x = e.clientX,
y = e.clientY,
stack = [],
elementMouseIsOver = document.elementFromPoint(x, y);

stack.push(elementMouseIsOver);

while (elementMouseIsOver.tagName !== 'HTML'){

elementMouseIsOver.style.pointerEvents = 'none';
elementMouseIsOver = document.elementFromPoint(x, y);

stack.push(elementMouseIsOver);
}

/* Now clean it up */
var i = 0,
il = stack.length;

for (; i < il; i += 1) {
stack[i].style.pointerEvents = '';
}

console.log(stack);
});

along with this css style:

.pointerEventsNone {
pointer-events: none;
}

Update:

Using classList to add/remove a pointer-events propriety is more elegant: as demonstrated in this fiddle and below:

function elementsAtLocation (x,y){
var stack= [], el;
do {
el = document.elementFromPoint(x, y);
stack.push(el);
el.classList.add('pointerEventsNone');
}while(el.tagName !== 'HTML');

// clean up
for(var i = 0; i < stack.length; i += 1)
stack[i].classList.remove('pointerEventsNone');

return stack;
}

Old browsers:
Using display:none for older browser, however this will trigger repaint/reflow: http://jsfiddle.net/Gwy2u/2/

How to Detect the Mouse Pointer Come From When Hover Elements

Try this code:

var getDirection = function (ev, obj) {    var w = obj.offsetWidth,        h = obj.offsetHeight,        x = (ev.pageX - obj.offsetLeft - (w / 2) * (w > h ? (h / w) : 1)),        y = (ev.pageY - obj.offsetTop - (h / 2) * (h > w ? (w / h) : 1)),        d = Math.round( Math.atan2(y, x) / 1.57079633 + 5 ) % 4;
return d;};
$('#yourDiv').mouseover(function (event) { var direction = getDirection(event, this); if (direction == 0) { $(this).html('Top side'); } else if (direction == 1) { $(this).html('Right side'); } else if (direction == 2) { $(this).html('Bottom side'); } else if (direction == 3) { $(this).html('Left side'); }});
#yourDiv {    width: 100px;    height: 100px;    background-color: red;    position: absolute;    top: 50px;    left: 50px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="yourDiv"></div>

Check if mouse is inside div

you can register jQuery handlers:

var isOnDiv = false;
$(yourDiv).mouseenter(function(){isOnDiv=true;});
$(yourDiv).mouseleave(function(){isOnDiv=false;});

no jQuery alternative:

document.getElementById("element").addEventListener("mouseenter", function(  ) {isOnDiv=true;});
document.getElementById("element").addEventListener("mouseout", function( ) {isOnDiv=false;});

and somewhereelse:

if ( isOnDiv===true ) {
// do something
} else {
return;
}


Related Topics



Leave a reply



Submit