Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JqueryUI tooltip on button click instead of hover to appear elsewhere

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"
               }
            });
});
like image 772
Swarne27 Avatar asked Oct 26 '12 06:10

Swarne27


1 Answers

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.

like image 64
Elliott Avatar answered Oct 14 '22 21:10

Elliott