I need to know when the mouse cursor leaves a div. So I hook up the mouseout event. However, if I move the mouse very quickly out of the div, the mouseout event doesn't fire. That's right: the mouse cursor was sitting still inside the div, it's now outside the div, and yet the mouseout callback hasn't been called. (It works fine if I don't move the mouse quite so fast.)
This is true in the latest Google Chrome by the way – so not just an "old browsers" problem.
A workaround:
A question about this problem has been posed before. Apparently it's just a fact of life, and the only workaround I've found is to manually monitor mousemove events, each time checking the cursor's x/y co-ordinates and seeing if they fall within the div’s bounding box, so you have more chances to "notice" if the cursor is no longer inside it.
Compared to letting the browser do all this natively, performing calculations on every pixel move is a bit of a performance hit. It's also tedious to code.
On to my question...
Why can't the browser can't reliably capture the mouseout event? If I can reliably tell when the mouse has left the div using the above workaround, why can't the browser do it?
I understand (from the answer linked above) that JavaScript doesn't try to interpolate "frames". Say if you put a mousemove handler on the document, and quickly move the mouse 200 pixels to the right in a perfect horizontal line, you might not get 200 mousemove events. A few will be missed. I don't have a problem with that.
But if some pixel movements are missed just as the mouse crosses the boundary of the div, why does it follow that the mouseout event should also be skipped? When the browser finally starts registering the mouse's position again (after a sudden fast movement), even if the mouse is now miles outside the box, the point is that it used to be in the box and no longer is. So why doesn't it then fire the mouseout event then?
I just don't get why this would be a hard problem for the browser vendors to solve. (But I trust there might be a good reason, which I'm too stupid to think of.)
I'm posting this question mainly out of curiosity, but I'm hoping the answer might give some insight that could help me work around the problem more efficiently. Also, any alternative workarounds (which are faster than the one presented above) would be welcome.
I know that you don't want a workaround, but you don't need to check mouse's x/y to know if you are in or out an element. You could simply check the element from which the mousemove event was fired. If you put a mousemove on document, the event will fire from one of its children, and you can compare that element with your element to know if it is one of its descendants.
Or you could go up the parentNode tree and stop if you find your element. Then you know you are inside the element and still in it, otherwise you reach the document and you are out.
Some browsers implement the mouseenter/mouseleave events that, I've noticed, are more accurate than mouseout. Prototype and jQuery have a workaround for browsers that don't implement these new events. Mouseleave does not fire from an element's children, whereas mouseout does.
You describe moving the mouse very quickly. When you stop, is the pointer still within the page? That is, is your mouse pointer still hovering over some part of the visible web page?
If it has gone outside, then it's not necessarily clear what the browser should do. The mouseout event should have a relatedTarget property that targets what the mouse pointer has gone into. If the mouse pointer is already outside of the page area, there would be no related target to point to.
Put another way, when the mouse leaves the page area, the browser stops tracking it and stops reporting its position. If you move your mouse fast enough, from the browser's perspective, the mouse simply disappeared. It's not until you bring the mouse back into the bounding box of the viewable page that the browser knows where it is, and then triggers all appropriate movement-based actions (like mouseout).
Why can't the browser can't reliably capture the mouseout event? If I can reliably tell when the mouse has left the div using the above workaround, why can't the browser do it?
I think you answered this one yourself when you said:
Compared to letting the browser do all this natively, performing calculations on every pixel move is a bit of a performance hit.
The browser does not interpolate between the frames, thus, as you stated it would demand a lot more resources and memory, which may be why it isn't "fixed".
If some pixel movements are missed just as the mouse crosses the boundary of the div, why does it follow that the mouseout event should also be skipped? When the browser finally starts registering the mouse's position again (after a sudden fast movement), even if the mouse is now miles outside the box, the point is that it used to be in the box and no longer is. So why doesn't it then fire the mouseout event then?
I don't know for sure, but I don't think it's a condition of "it was in and now it's out". Instead, it's whether it crosses that boundary (if MouseX - ElemOffsetX= 1). I agree, it doesn't make as much sense, but it could be because if you set the value to > 1 it would trigger the event multiple times. Otherwise it would have to keep track of the events, which is not in JS nature, seeing how it just adds events asynch to a stack.
What you could try is using jQuery's mouseleave event. This does two things, which delays the firing of the event:
It traverses the DOM tree to see if it truly left the element
I think it implements a timeout call, which should solve the interpolation problem that you noticed.
I found your question and the lack of other clear answers useful because it told me that I had to create a workaround. Which I did using the ideas presented in your question and the other contributors.
I have same problem when I use jquery mouseleave elem.bind('mouseleave', data, mouseLeavesZone);
The problem is intermittent and may be related to a busy CPU on the client. Say, for example, the CPU is busy elsewhere when your mouse moves out of a div. Then it seems logical that this could be the cause of the bug. I agree; this should be fixed by the browser vendors.
See http://jsfiddle.net/bgil2012/gWP5x/1/
(Aside: My JQuery code needs to use older jQuery methods because it has to run in Drupal 7 which is running jQuery 1.4, at this time and without applying patches that are coming).
I ran into this problem a few times and I came to accept the issue as a fact of life. But depend on your needs, you can just use CSS as I did. For example, if I just want to show/hide an element base on another element got hovered, then CSS is the way to go. Here is a working, reliable example:
.large {
width: 175px; height: 175px;
position: absolute;
border-radius: 100%;
/*hide the glass by default*/
top: -9999px;
left: -9999px;
opacity: 0;
transition: opacity .2s ease-in-out;
z-index: 100;
pointer-events: none;
}
.small:hover + .large {
opacity: 1;
}
http://codepen.io/tanduong/pen/aBMxyd
Here's a simple workaround.
In your onMouseOver listener, you can add a 'mousemove' listener to the window:
<div onMouseOver={() => {
setMouseOver(true)
let checkMouseLeave = (e: MouseEvent) => {
if (rootRef.current
&& !rootRef.current.contains(e.target as HTMLElement)) {
setMouseOver(false)
window.removeEventListener('mousemove', checkMouseLeave)
}
}
window.addEventListener('mousemove', checkMouseLeave)
}
></div>
Then you can check on each mouse move until the mouse is outside of your div (rootRef.current in our example).
Related
For example, when using jquery ui draggable (http://jqueryui.com/draggable/) the object follows the mouse rather than moving with the mouse. It seems like there is a one frame difference in position.
Why is that? Is there a way to get around this?
The animation is chasing your mouse's movement because it has to wait for the mousemove event.
And, while the event fires fairly rapidly as you move the mouse pointer, it still fires after the pointer has actually moved. So, the box' position is always being updated to where the pointer was if it's still in motion.
The event will also be throttled by the (mostly) single-threading of JavaScript. If the engine is busy, including with a previous trigger of the event, the most recent trigger will have to wait for the engine to again become idle.
And, counting those triggers as frames, jQuery also employs easing so the box' position doesn't jump around oddly when there are irregularly-spaced frames.
You could try to build a more efficient function, but it more or less depends on the browser, and system. If your browser and/or your system is slow, then you will experience a lag while dragging or following the mouse.
I experienced no lag with the link you provided.
I was trying to answer an issue with custom drop down, but challenged by an inconsistent behavior in Chrome and Firefox.
DEMO: http://jsfiddle.net/fyeht/ [Added scroll event for more clarity]
See below image, The list items can be navigated using arrow keys.
To Reproduce the issue:
Open console in Chrome (F12)
Click on an item in the list (you would notice some events getting logged in the console)
Use down arrow key to navigate to the next item in the list
Finally, the issue is noticed when you reach the last item in the view and hitting down arrow would scroll. Check the log to see 'scroll', 'mouse enter' and 'mouse move' [check the new demo]
The issue is after reaching the end of items in view, it scrolls. Even though the mouse is untouched, it triggers mouseenter and mousemove events in Chrome. In FF, on scroll it triggers just the mouseenter which make sense.
Question(s):
Why is mousemove triggered when mouse is untouched?
Is this just browser inconsistency? Could not find documentation on events triggered when scrolling? (never knew it did)
Submitted a bug report: https://code.google.com/p/chromium/issues/detail?id=241476
In your example, I see that both Chrome and FF are firing mouseenter DOM events whenever the mouse is left hovering over the <ul> and pressing the key down triggers the browser to scroll in order to bring the selected <li> into view.
However, only Chrome is additionally triggering mousemove events. One obvious difference already in the mouseenter event objects that the two throw is that for Chrome, MouseEvent.offsetX and MouseEvent.offsetY values are included, whereas in FF these properties are undefined. So, when that enter is triggered Chrome has already decided the mouse "has moved".
Since the MouseEvent.screenX and MouseEvent.screenY event context values do not change between scroll-triggered MouseEvent instances, one could perhaps distinguish between an "artificial" mouseenter / mousemove event and an "authentic" one by storing these values from prior events.
DOM Event Specification
The DOM Level 2 Event Specification for mousemove reads:
The mousemove event occurs when the pointing device is moved while it is over an element.
The Level 3 spec (working draft) is essentially the same:
A user agent must dispatch this event when a pointing device is moved while it is over an element.
Seems like it could down to whether one interprets "is moved" relatively or not.
Also, in the section of the Level 3 spec on mouse event order, it states that when a pointer is moved into an element, it triggers mouseover, mouseenter, and mousemove, in that order. Every case that is specified there always has those three together, so perhaps one might interpret it that if you are going to trigger the mouseenter event, you should also be triggering the mousemove event which corresponds to entering the element.
This is a nice demo.
In Chrome mouse movement for elements is definitely relative. In chrome I can get keydown and scroll events only if the mouse pointer is over the scroll bar. I can also get scroll only events if i use the wheel to scroll and leave the mouse over the scroll bar. It is and isn't very odd that scroll by dragging causes "mouse move", and "mouse over" events.
Not only are mouse move and mouse over events produced in profusion by the browser they are not a very good indication of a users intent. Infact these events are a useful entropy source.
To the degree that there are some minor differences this is in the context of how useful these "micro events" are individually. To work with them you must devise a way to filter them for user intention you want to link to higher level actions. Any reasonable method you choose to make sense of these events will probably detect these move - on scroll events as garbage. This is where your point is really worth noting and taking under consternation.
A first stage would be to Filter out events based on the elements and values of coordinates. It might help to create a state machine model. You might register and registered handlers in response to other events. You've identified this case where you'd want to change responsive state if or reaction criteria if a key element has a scroll bar. IF an element or it's parent has a vertical scroll bar throw out mouse moves with relatively high X values.
You might want to also ignore mouse overs if it's fired with a mouse move in that context. It starts to become impractical to handle each of these micro event one at a time even if you are changing state by registering or deregistering handlers. More information can be extracted by creating an event sequence fifo buffer.
Register event handlers to add a new event to the buffer. You might also want to collect information from timer events in this buffer to establish more context. You might create an object that keeps a fifo in an array. This would be like a queue but not in the sense of it being a place where the events are waiting to be processed. Instead your program is waiting to calculate patterns in the buffer and based on the patterns fire higher level events, accept or reject different types of events and extend, contract or save the contents of the buffer. You can then evaluate move events for changes in x and y and also create conditions given the patter of scroll mouse over and mouse move events you've demonstrated.
I really doubt there's a browser inconsistency here. You should create a mousemove event that prints out the x and y coordinate. You'll probably see that the mouse has indeed moved a little bit. If that's the case, try using the plugin hoverIntent to eliminate issues like this.
EDIT:
Using the up and down arrow keys, I'm now able to replicate the issue. Yeah, it sure looks like some kind of bug! I bet the mousemove coordinate delta is tiny. Maybe the cursor moves one or two pixels? I would say, to overcome this, add a check to the mousemove function that compares previous mousemove's x-y coordinates to the current mousemove's x-y coordinates. Determine if it's more than just a few pixels. If so, you know it's a real mousemove. If it's less, you can chalk that up as a chrome bug.
FURTHER EDIT:
It seems like you uncovered a bug where mousemove is being fired in chrome when it probably shouldn't be. There may be workarounds that you could figure out if you hack it enough. But the best solution might be just to avoid using mousemove in this situation. In general, mousemove is one of those expensive events that should be used only when you really need it.
This is not a bug. The mousemove is relative to element that the event is attached to. In your case, you see that your mouse is not moving because you took the browser window as the reference. But for that scrolling list, whenever the list is scrolled, the mouse pointing over some element of the list moved to over different element
Imagine that you as the Earth, a cup of coffee stand still on a table as the mouse, the scrollable list as the Sun : if you (window) don't move, the position of the cup of coffee (mouse) is at the same place for you; but for the Sun (list), it will see that the Earth and the cup of coffee are both moving.
I have buttons which have been given click depth (i.e. they move down a few pixels on :active state) but they are causing problems in that sometimes the button is clicked and nothing happens.
<button>Button</button>
button:active {
margin-top: 5px;
}
I have illustrated the problem in a jsfiddle:
http://jsfiddle.net/helenst/vUU55/
In Chrome, there is a thin strip above and below the text, height equal to the click depth, in which click events do not fire. (e.g. try clicking a pixel or two above the 'B') Both mousedown and mouseup are received, but click does not fire.
In Firefox and Opera, there is an area of the same size at the top of the button in which the mouse click does not respond. I find this slightly more logical in that the mousedown is inside the button but the mouseup is outside it. If I click down in this area but drag the mouse back into the button before releasing it, the click is activated.
However, it still doesn't completely make sense - if I wrap a container around the button (so that all button states are contained inside it), and detect events on the container, the problem still occurs.
If I remove the click depth, everything is fine.
I suppose I could make it respond to mousedown events and then detect mouseups on the document, this might get around it - but it violates normal button behaviour and I'd like to have a non-javascript solution. Can anybody help?
If you can make the :active style work using padding-top (or anything inside the border - even setting the border-top to 5px could work, sorry untested). Though of course that breaks your styling somewhat; a background top-aligned horizontal bar image could replace the top border if you need it in there, though a hacky idea).
Apologies, cannot test in newer browsers at present. I've seen this type of button several places before but cannot remember any offhand to test how well they cope with this issue/what code they use.
Almost made this a new answer, but SO is less fond of that:
The other alternative that I've seen, though harder to add really big depth (movement), is to use inset and outset in the border styles.
I have several pages that are all very similar. They have some javascript rollover links (images are preloaded, then there is a onMouseOver event that calls an image swap function and finally, there is a onMouseOut event that restores the original image).
When the user clicks on a rollover link that points to another page that has a rollover link on the exact same position, the image on the new page would be expected to load on the "over" state. This is not the case in Chrome and Safari (IE and Firefox work as expected).
So... On page load, is there a way to check if the mouse is already hovering the image to swap it right away? Something like "OnMouseAlreadyOver"?
Thank you.
If you using jQuery, it works without any problems!
http://jsfiddle.net/beuae
(not only for buttons, for divs also)
Actually, jQuery is a very good framework which assures everything goes as you expect, and cross-browser. This example confirms it.
The W3C standard says
onmouseover = script [CT]
The onmouseover event occurs when the pointing device is moved onto an element. This attribute may be used with most elements.
onmousemove = script [CT]
The onmousemove event occurs when the pointing device is moved while it is over an element. This attribute may be used with most elements.
mouseover is fired on moving over the boundary of the object. mousemove happens when the mouse is already over the element.
You may need to use onmousemove (or even both).
You may need to actually do the calculation based on the element position and the mouse cursor position.
//Get Mouse Position
document.onmousemove=getMouseCoordinates;
function getMouseCoordinates(event){
ev = event || window.event;
mouseX = ev.pageX;
mouseY = ev.pageY;
}
You can't without passing a variable to the other page or using cookies to track which was hovered (and that will fail over if people do change their mouse position)
In theory you could check the mouse position and the button position however there is no way to get the mouse position unless an event is triggered, so the mouse has to move and if it move the CSS :hover should get triggered.
It's a minor issue tho, I doubt most people are going to click a link, wait for the next page and then expect that link to be hovered and ready to click again (why wouldn't anyone one to keep clicking the same button unless it does different things)
From a UX point of view I wonder if webkit doesn't have the best approach here, why port the action of one page to another.
You can use document.getElementFromPoint(mouseX, mouseY) to get the element, but the only way to get the cursor's position is via an event. The problem is, the only events are clicks and mouse movements, which require user input from the beginning, which is what you're trying to avoid.
In short, no, it's not possible to do with JavaScript. You're left with using CSS.
This question already has answers here:
How can I make page scrolling trigger mouseover events?
(3 answers)
Closed 3 years ago.
I have the fancy Apple mouse that detects finger movements such as "swipe" and "scroll".
Leaving the cursor fixed on the screen, but using my finger to scroll down my page, the cursor (although fixed) naturally moves over different elements, because the elements are moving themselves.
My problem is that when doing that, the appropriate mouseover/mouseenter callbacks don't get called when he mouse cursor is directly above them.
How can I solve this problem?
Most browsers that I've used don't fire mouse events when the page scrolls. You could try listening to the onscroll event and using document.elementFromPoint to determine what element has moved underneath the mouse cursor when the onscroll event fires.
Jquery's mousemove method is a nice solution here as it does get triggered when the mouse is rolled into an element as you scroll, even while the mouse has remained static.
You could even trigger the mouseenter event on mousemove as long as you include some kind of flag/state-check to ensure your mouseenter code doesn't get executed repeatedly on mousemove.
I dont think you can... short of having a function that runs on a timer to check the position of the mouse against the elements, but the performance hit on that would be astronomical to say the least. Probably should file a bug report with the browser manufacturer and check other browsers to see if the behavior is replicated - Which I'm guessing it will because dont think any browser will fire a mouseover/mouseenter event if the mouse was not physically moved.