JqueryUI tooltip on button click instead of hover to appear elsewhere

30,186

The easiest way is to remove the title attribute of myBtn and move your tooltip onto another element. For example:

<a id="myTooltip" title="Message"></a>

Then you can do:

$('#myTooltip').tooltip({
    //use 'of' to link the tooltip to your specified input
    position: { of: '#myInput', my: 'left center', at: 'left center' }
});

$('#myBtn').click(function () {
    $('#myTooltip').tooltip('open');
});

Similarly you can close the tooltip with

$('#myTooltip').tooltip('close');

To automatically close the tooltip after opening you just need to call the close method inside the open event:

$('#myTooltip').tooltip({
    open: function (e) {
        setTimeout(function () {
            $(e.target).tooltip('close');
        }, 1000);
    }
});

Using e.target (as this will not work inside the open event) and setTimeout() to set a time limit after which the tooltip will close.

Share:
30,186
Swarne27
Author by

Swarne27

Currently a Software Engineer at Melbourne based company. Former Software Engineer at www.ustocktrade.com (Colombo Sri Lanka)

Updated on March 11, 2020

Comments

  • Swarne27
    Swarne27 about 4 years

    I am using JQueryUI tooltip to display some dynamic messages to the user. Basically I want to display the tooltip on top of an input field when a user clicks a button.

    The way I have coded it works only when hovering on top of the button, and in JQueryUI examples there's no help on achieving this scenario. How do I differ from hover effect and make it work with click event of the button? How can I achieve this?

    I'm using jquery-ui-1.9.0.custom.js and jquery-1.8.2.js for this.

    HTML Code: I want to display the message on top of this input box

    <input id="myInput" type="text" name="myInput" value="0" size="7" />
    

    The button which I click in-order to popup tooltip

    <input id="myBtn" type="submit" name="myBtn" value="myBtn" title="this is not used" class="myBtn" />
    

    JQuery Code

    $(document).ready(function() {
        $(".myBtn").tooltip({
                   content: function () {
                      return '<span id="msg">Message</span>';
                   },
                   position: {
                      my: "center bottom",
                      at: "center top"
                   }
                });
    });
    
  • Swarne27
    Swarne27 over 11 years
    I added the close event inside another user behavior and it works. Thx for the help @Elliott
  • Swarne27
    Swarne27 over 11 years
    what if i want to close the tooltip automatically after opening it programmatic?
  • Swarne27
    Swarne27 over 11 years
    Thx @Elliot your explanation helped me :)