Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show and hide bootstrap tooltip using javascript

I need to show bootstrap tooltip when user click on element and condition is false. I've written code for this:

<div data-toggle="tooltip" title="You must to log in!" class="stars">425</div>

and Javascript:

$(".statistics .stars").click( function(){
    if (! user.isLogin){
        $(this).tooltip("show");

        setTimeout(function(){
          $(this).tooltip( 'hide' );
        }, 2000);   
    }
});

When I don't click I can see default tooltip on hover (I don't need it) and when I click, tooltip don't hide after 2 seconds. How to solve this problems?

like image 853
Alexander Seredenko Avatar asked Jun 21 '16 07:06

Alexander Seredenko


People also ask

How do I show tooltip in bootstrap?

How To Create a Tooltip. To create a tooltip, add the data-toggle="tooltip" attribute to an element. Note: Tooltips must be initialized with jQuery: select the specified element and call the tooltip() method.

What is tooltip in JavaScript?

JS Tooltip (tooltip. js) The Tooltip plugin is small pop-up box that appears when the user moves the mouse pointer over an element. For a tutorial about Tooltips, read our Bootstrap Tooltip Tutorial.


2 Answers

First you need to set tooltip to be manual, now it will not popup on hover

$('div').tooltip({trigger: 'manual'});

After that you need to save div element before using it inside setTimeout because this outside of setTimeout and this inside of setTimeout is different.

$('div').click(function(){
  var tt = $(this);
  if (! user.isLogin){
    tt.tooltip("show");

    setTimeout(function(){
      tt.tooltip( 'hide' );
    }, 2000);   
  }
});

Here is the updated jsfiddle

like image 90
Almis Avatar answered Sep 28 '22 00:09

Almis


This should solve your problem:

$(".statistics .stars").click( function(){
    if (! user.isLogin){
        var $el = $(this);
        $el.tooltip("show");

        setTimeout(function(){
            $el.tooltip( 'hide' );
        }, 2000);
    }
});
like image 29
Tim Hysniu Avatar answered Sep 27 '22 23:09

Tim Hysniu