Search code examples
javascriptjquerytwitter-bootstraptooltip

Bootstrap tooltip disappears after second 'show'


I want to produce a manual tooltip based upon some user input. The easiest way was to hide all tooltips and then show the relevent ones.

I've reduced my code down to the bare essentials, and my tooltip keeps disappearing after the second "show".

I'm using bootstrap 3.3.4 and jquery 2.1.3

Is there a problem with doing a show immediatly after a hide or am I missing something in my code?

<input id="check" type="checkbox">

<script>
    var toolTipData = {
    placement: 'right',
    title: 'Checkmark checked',
    trigger: "manual"
};
$('#check').tooltip(toolTipData);

$(document).on('change', '#check', function () {
    $('#check').tooltip("hide");
    if (document.getElementById("check").checked) {
        $('#check').tooltip("show");
    }
});
</script>

Here's a jsfiddle: https://jsfiddle.net/bbrally/4b9g0abh/


Solution

  • You're experiencing a race condition between when the "hide" event happens and when the "show" event happens. Per the documentation the "hide/show" events actually return to the caller before the "hidden/shown" events fire.

    http://getbootstrap.com/javascript/#tooltips Scroll down to the "Methods" section under tooltips ...Returns to the caller before the tooltip has actually been hidden...

    ...Returns to the caller before the tooltip has actually been shown...

    I'm not suggesting the code below is a solution (though, it might be good enough?), but an explanation as to what you're running into. Specifically the timeout value of 250ms will slow it down enough such that it works as you're intending.

    var toolTipData = {
            placement: 'right',
            title: 'Checkmark checked',
            trigger: "manual"
        };
        $('#check').tooltip(toolTipData);
    
        $(document).on('change', '#check', function () {
            $('#check').tooltip("hide");
            if (document.getElementById("check").checked) {
                setTimeout(function() {
                    $('#check').tooltip("show");
                }, 250);
            }
        });
    

    Hope this helps.