javascripthtmljqueryjquery-eventsflot

jQuery flot the tooltip will not hide when I move the mouse quickly out of plot


Please have a look at the example of jQuery flot with tooltip, which is at http://www.flotcharts.org/flot/examples/interacting/

When I put the mouse and move the normally the tooltip appears and disappears normally.

However when I move the mouse quickly out of plot, the tooltip will remain.

Please see below animated gif which shows slow and quick mouse movement.

enter image description here

The main part code which handles the hover is as below:

$("#placeholder").bind("plothover", function (event, pos, item) {

            if (item) {
                var x = item.datapoint[0].toFixed(2),
                    y = item.datapoint[1].toFixed(2);

                $("#tooltip").html(item.series.label + " of " + x + " = " + y)
                    .css({top: item.pageY+5, left: item.pageX+5})
                    .fadeIn(200);
            } else {
                $("#tooltip").hide();
            }
    });

I think it is because when I move the mouse quickly the $("#tooltip").hide(); executes when the $("#tooltip").html is not rendered.


Solution

  • #placeholder, which is the graph container, is binded to the plotover event.
    So when such event occur on this container element, the script checks if there is an item returned in order to decide to show or hide the tooltip.

    Now when your mouse is outside this container, there is no more plothover event triggered. So the script is not executed to hide the tooltip.

    To fix that, I would add a script which would hide the tooltip when the mouse leaves the container like this:

    $("#placeholder").on("mouseleave", function(){
      $("#tooltip").hide();
    });
    

    Also, notice that .bind() is deprecated. It is preferable to use .on().


    EDIT

    I didn't think about delays in my first answer.
    When passing your mouse fast on the chart item... There is something like a 600ms delay for the tooltip show animation.

    So the mouseleve event is trigered too early to close it.

    Try this now:

    $(document).on("mousemove",function(e){
      if ( $(e.target).closest("#placeholder").length == 0 ){
        $("#tooltip").hide();
      }
    });
    

    So now, on mousemove, this script will check if the mouse is over the chart container on any of his childs. If not, it will hide the tooltip.