简体   繁体   中英

How to make mouseenter and mouseleave events work in harmony?

I have a website and I need when the user hovers the mouse over stars to show a popover and when the mouse leaves to hide that popover.

I am using jquery to do that like the followings:

  $('.stars-rating-overview').mouseenter(function () {
    setTimeout(function () {
        $("#starRatingStats").show();
    }, 300);
   }).mouseleave(function () {
    setTimeout(function () {
        $("#starRatingStats").hide();
    }, 300);
   });

The problem I have with the above code is sometimes popover shows and does not disappear as if the mouseleave didn't trigger.

Could you please guide me to how I can make those two events work in harmony so that the popover does not show immediately when the user hovers over stars accidentally and to handle the case where the popover left shown after the mouse leaves stars?

i suggest you to clear timeout, before beginning another:

  var ts = 0, th =0;
  $('.stars-rating-overview').mouseenter(function () {
    clearTimeout(th);
    ts = setTimeout(function () {
        $("#starRatingStats").show();
    }, 300);
   }).mouseleave(function () {
    clearTimeout(ts);
    th=setTimeout(function () {
        $("#starRatingStats").hide();
    }, 300);
   });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM