最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trigger mouse enter event on page load if cursor already on the element - Stack Overflow

programmeradmin0浏览0评论

I have binded a mouseenter event with some elements on my page, I am checking if the page has been loaded before allowing the actual functionality of mouseenter to run. Everything works fine but the problem is, if a user already places the cursor on the element before the page loaded, the user is then forced to first move out of the div and then again move cursor inside the div for the event to fire which makes it pretty awkward.

Is there a way by which I can check where the cursor is on page load, as in, on which element it is hovering and trigger the mouseenter event accordingly?

I have attached a snippet for better understanding of my problem.

Thanks, in advance.

let pageLoaded;

/* assuming page load takes 3 seconds*/
window.onload = () => setTimeout(() => pageLoaded = true, 3000)

$(document).ready(() => {

  $('#box').mouseenter(() => {

    /* continue only if the page has been loaded */
    if (!pageLoaded)
      return;

    $('body').append('mouse entered after page load <br>')


  })
})
#box {
  height: 150px;
  width: 150px;
  background-color: green;
  margin:10px;
  cursor:pointer;
  float: left;
}

 p {
  font-style: italic;
 }
<script src=".1.1/jquery.min.js"></script>

<div id="box">
</div>

<p> I want the mouseenter event to fire (on page load ~ "3 seconds here"), if the cursor was already placed inside the green box before the page loaded. </p>

I have binded a mouseenter event with some elements on my page, I am checking if the page has been loaded before allowing the actual functionality of mouseenter to run. Everything works fine but the problem is, if a user already places the cursor on the element before the page loaded, the user is then forced to first move out of the div and then again move cursor inside the div for the event to fire which makes it pretty awkward.

Is there a way by which I can check where the cursor is on page load, as in, on which element it is hovering and trigger the mouseenter event accordingly?

I have attached a snippet for better understanding of my problem.

Thanks, in advance.

let pageLoaded;

/* assuming page load takes 3 seconds*/
window.onload = () => setTimeout(() => pageLoaded = true, 3000)

$(document).ready(() => {

  $('#box').mouseenter(() => {

    /* continue only if the page has been loaded */
    if (!pageLoaded)
      return;

    $('body').append('mouse entered after page load <br>')


  })
})
#box {
  height: 150px;
  width: 150px;
  background-color: green;
  margin:10px;
  cursor:pointer;
  float: left;
}

 p {
  font-style: italic;
 }
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="box">
</div>

<p> I want the mouseenter event to fire (on page load ~ "3 seconds here"), if the cursor was already placed inside the green box before the page loaded. </p>

Share Improve this question asked Nov 22, 2018 at 14:10 saibbywebsaibbyweb 3,2642 gold badges36 silver badges55 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

[EDITED] i use mousemove inside the box, but it needs that you move the mouse 1px or more, here is the code

let pageLoaded;

/* assuming page load takes 3 seconds*/
window.onload = () => setTimeout(() => pageLoaded = true, 3000)

$(document).ready(() => {
//created for control and trigger event only one time
var outControl = true;
  $('#box').mousemove(() => {
    /* continue only if the page has been loaded */
    if (!pageLoaded)
      return;
	if(outControl){
		outControl = false;
		$('body').append('mouse entered after page load <br>')
	}
  })
  
  $( "#box" ).mouseout(function() {
	outControl = true;
	$('body').append('mouse left after page load <br>')
});
})
#box {
  height: 150px;
  width: 150px;
  background-color: green;
  margin:10px;
  cursor:pointer;
  float: left;
}

 p {
  font-style: italic;
 }
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
</div>

<p> I want the mouseenter event to fire (on page load ~ "3 seconds here"), if the cursor was already placed inside the green box before the page loaded. </p>

[EDIT] Sorry bro, but its not possible get mouse position before the mouse move, the browser does not have this information before the mouse move, and you may think "then I'm going to fire the event manually at the top of the page", this does not work either :(

[SECOND_EDIT] In this case, i use localStorage, is not possible teste this in code sniped, but paste this in the same example but at local page, this works fine for me. This code is not very good (i do not have mutch time, sorry), but you can use localStorage as a kick-start to find a better solution

let pageLoaded;

window.onload = () => setTimeout(() => pageLoaded = true, 3000)

$(document).ready(function (e){
  $('#box').mousemove((e) => {
    /* continue only if the page has been loaded */
    if (!pageLoaded){
        if(outControl){
            localStorage.setItem("mouseHoverElementId",e.target.id)
            $('body').append('mouse entered before page load <br>')
            outControl = false;
        }

        return;
        }
    if(outControl){
        localStorage.setItem("mouseHoverElementId",e.target.id)
        outControl = false;
        $('body').append('mouse entered after page load <br>')
    }
  })

  $( "#box" ).mouseout(function() {
    localStorage.setItem("mouseHoverElementId","")
    outControl = true;
    !pageLoaded ? $('body').append('mouse left before page load <br>') : $('body').append('mouse left after page load <br>')
});
//created for control and trigger event only one time
var outControl = true;
if(localStorage.getItem("mouseHoverElementId") != ""){
        $('#'+ localStorage.getItem("mouseHoverElementId")).mousemove();
    }
})

** Edited answer ** Since hiding the box is not an option, use a boolean which tracks if the user is on the box using mouseenter and mouseleave before page load. Then, if after the page is loaded the boolean is true, call the same logic as the mouseover event manually. Then remove the mouseenter and mouseleave listeners.

let pageLoaded;
let insideBox = false;

/* assuming page load takes 3 seconds*/
window.onload = () => setTimeout(function() {
  pageLoaded = true;
  if (insideBox) {
    // Manually call the mouseover logic here
    $('body').append('mouse entered BEFORE page load <br>')
  }
  $('#box').off('mouseenter').off('mouseleave')
}, 3000)


$(document).ready(() => {
$('#box').on('mouseenter', function() {
   insideBox = true;
})
$('#box').on('mouseleave', function() {
   insideBox = false;
})

$('#box').mouseover(() => {
    /* continue only if the page has been loaded */
    if (!pageLoaded)
      return;

    $('body').append('mouse entered after page load <br>')
  })
})
#box {
  height: 150px;
  width: 150px;
  background-color: green;
  margin:10px;
  cursor:pointer;
  float: left;
}

 p {
  font-style: italic;
 }
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="box">
</div>

<p> I want the mouseenter event to fire (on page load ~ "3 seconds here"), if the cursor was already placed inside the green box before the page loaded. </p>

You could register a mousemove listener which is executed once with jQuery.one and store the mouse position. Then you get the position of your reference element and pare them. If elements are coliding just use jQuerys trigger method.

I would suggest you create a region within your page, for example, the different sections of the page and use if statements to check the mousecursor position on page load, then run whatever you want to if the check es out true. That's my suggestion.

发布评论

评论列表(0)

  1. 暂无评论