Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide tooltip after some time

I want an effect, when someone hovers over an element, he sees a tooltip for a few seconds after which the tooltip disappears, even when the mouse is still on the element. This is what I have:

<div data-sentence-tooltip="yes" data-tooltip-content: "some content"> some text </div>
$('[data-sentence-tooltip="yes"]').tooltip({title: function(){return $(this).attr('data-tooltip-content')}});

I tried the following two, based on other related SO questions:

setTimeout(function(){$(".tooltip").fadeOut("fast");}, 2000);

and

jQuery.fn.delay = function(time,func){
    return this.each(function(){
        setTimeout(func,time);
    });
};

$('[id^="tooltip"]').delay(2000, function(){
    $('[id^="tooltip"]').fadeOut('fast');
    }
);

But I think I know why none of these are working. Probably because .tooltip or id=tooltip* gets added to DOM on-the-fly.

Ref:

  1. jQuery tooltip, hide after.. time
  2. jquery tooltip set timeout
like image 306
The Wanderer Avatar asked Feb 27 '26 21:02

The Wanderer


2 Answers

Taking cue from Zoheiry answer, this is what I finally did:

$('[data-sentence-tooltip="yes"]').on('mouseover', function(){
    setTimeout(function(){
    $('#enclosingParentDiv').find('.tooltip').fadeOut('fast');
  }, 1000);
}); 

Couple of points to note:

  1. I applied the "mouseover" to each div, because the user is hovering the mouse on the content in the div
  2. I search for .tooltip in the parent div because tooltip gets added as sibling.
like image 143
The Wanderer Avatar answered Mar 02 '26 09:03

The Wanderer


Add a function like so

$('[data-sentence-tooltip="yes"]').on('mouseover', function(){
  // if the tooltip is a child of the element that is being hovered on
  // then write this.
  setTimeout(function(){
    $(this).find('.tooltip').fadeOut();
  }, 2000);

  // if the tooltip is a sibling of the element being hovered on
  // write this
  setTimeout(function(){
    $(this).parent().find('.tooltip').fadeOut();
  }, 2000);
});

This ensures that your code will only look for the .tooltip after you have hovered on the item which displays it.

like image 39
Alizoh Avatar answered Mar 02 '26 09:03

Alizoh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!