开发者

Is cursor over element (on page load)?

开发者 https://www.devze.com 2023-02-25 15:13 出处:网络
I have a .hover() action assigned to an element to hide/show something depending on the curs开发者_开发问答or being over it. The problem I am running into is that when the page loads and the cursor is

I have a .hover() action assigned to an element to hide/show something depending on the curs开发者_开发问答or being over it. The problem I am running into is that when the page loads and the cursor is OVER the element it doesn't register as being over because its not firing the mouseenter event.

Is there a another way to tell if the cursor is over a desired element?


Using the mouse position on page load you could call

var currentElement = document.elementFromPoint(x, y);

then if the element found at that position is the one with the hover event. You can trigger that hover event manually

$(currentElement).trigger('hover');


If you hide the element(s) until the page is done loading and then show them all at once, will your mouseover event now fire?

<div id='allmyelementsinhere' style='display:none'>

then use javascript to remove the display:none on page load.

I'm thinking that your mouseevent will fire as soon as you display the elements.


I also had this issue with next and previous navigation buttons that navigate between consistently designed pages.

A user would click next to go to the next page, and because their mouse was in the same position on the page load of the second page, they were able to click next again to continue navigating through the collection of pages. Essentially a convenient next/previous UI.

Except of course that the hover state didn't display on page load for the second and subsequent pages.

So I added a url parameter (action='next or action=prev) and then on load I put the next or previous button into the hover state if the relevant url parameter is present. If the user has somehow moved their mouse and isn't over the button then you do get a button incorrectly in it's hover state until the first mousemove event.

It's not perfect and it only suits this specific circumstance where a user is using a consistent UI within pages on your site, but as this sort of UI is a fairly common - especially in blogs/galleries I though I'd mention it.


Here is the jquery method to track mouse position starting from page load.

(function($) {
  $.mousePos = {x: 0, y: 0};
  var recordPos = function(e) {
    $.mousePos.x = e.pageX;
    $.mousePos.y = e.pageY;
  };
  $(document).mousemove(recordPos).mouseover(recordPos);
})(jQuery);

This will populate $.mousePos.x and $.mousePos.y as soon as the mouse starts to interact with the page.


Script to get mouse coordinates on load

0

精彩评论

暂无评论...
验证码 换一张
取 消