Jquery Mouseover and Mouseleave Tooltips (delay and how to cancel if mouse is moved before SetTimeOut)

273 views Asked by At

O.k. so in a $(document).ready(function() {...}

I have code that binds an event to all links with a class of .user_tooltip which makes an ajax call to get the user's info.

It works well. It displays the tooltip next to the link no matter where it is in the page.

Unfortunately I cannot, for the life of me, figure out how to add a delay and a cancel on the delay when the mouse leaves the link before the timeout.

Basically the tool tips display immediately, and it's just annoying and unusable.

How do I add a delay so the ajax doesn't fire until...500ms of mouseover/mouseenter and cancels if mouseleave happens before the 500ms?

I've tried everything I can think of and it's just not working.

Code:

//user_tooltips
    $(document).on('mouseover', '.user_tooltip', function(e){
      e.preventDefault();
      var user_tooltip_link = e.target.href;
      user_tooltip_link = user_tooltip_link.split("/");
      user_tooltip_name = user_tooltip_link[user_tooltip_link.length-1];
      var user_tooltip_username = $("#user_tooltip_username").html();
      if(user_tooltip_username != user_tooltip_name){
        var user_tooltip_ajax_request = $.ajax({
          type: "GET",
          beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
          url: '/user_tooltip_info/' + user_tooltip_name
        });
      }

      displayDiv("user_tooltip", getLeft(this.id) + 45, getTop(this.id));
    });

    $(document).on('mouseleave', '#user_tooltip', function(e){
      $("#user_tooltip").hide();
    });

   $(document).on("click", function(){
    $("#user_tooltip").hide();
  });
1

There are 1 answers

9
Barmar On

Start a timer in the mouseover handler to display the AJAX call. Then cancel the timer in the mouseleave handler.

Use an arrow function for the timeout so that this will be captured.

let tooltip_interval;

$(document).on('mouseover', '.user_tooltip', function(e) {
  e.preventDefault();
  var user_tooltip_link = e.target.href;
  user_tooltip_link = user_tooltip_link.split("/");
  user_tooltip_name = user_tooltip_link[user_tooltip_link.length - 1];
  var user_tooltip_username = $("#user_tooltip_username").html();
  if (user_tooltip_username != user_tooltip_name) {
    tooltip_interval = setTimeout(() => {
      $.ajax({
        type: "GET",
        beforeSend: function(xhr) {
          xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
        },
        url: '/user_tooltip_info/' + user_tooltip_name
      });

      displayDiv("user_tooltip", getLeft(this.id) + 45, getTop(this.id));
    }, 500);
  }


});

$(document).on('mouseleave', '.user_tooltip', function(e) {
  clearTimeout(tooltip_interval);
  $("#user_tooltip").hide();
});

$(document).on("click", function() {
  $("#user_tooltip").hide();
});