tooltip not showing on first mouseover

2019-02-14 20:41发布

问题:

I am using jquery-ui's (1.10.2) tooltip widget and I am experiencing an annoying error. The tooltip won't show on the first mouseover. It does when I mouseout and re-mouseover and everytime after that. Just not the first time. This is my code:

HTML:

<img src="btn-tooltip-info.png" class="tooltip" title="Your text here"/>

javascript:

$(document).ready( function() {

    $(document).on("mouseover", ".tooltip", function(e){
        $(this).tooltip({
            content: function() {
                return $(this).attr('title');
            },
            position: { my: "left+15 center", at: "right center" }
        });
    });
});

I'm using on() because other processes might dynamically change the html after initial load. I'm at a loss here, any insights would be greatly appreciated. Thanks in advance for any help.

回答1:

It is because the tooltip is triggered on mouseover but when the first mouseover happens there is no tooltip widget associated with the element.

A hack you can use in this scenario is to check if the widget is initialized for the element, if not initialize the widget and then manually trigger the mouseover event again

$(document).ready( function() {

    $(document).on("mouseover", ".tooltip", function(e){
        if(!$(this).data('tooltip')){
            $(this).tooltip({
                content: function() {
                    return $(this).attr('title');
                },
                position: { my: "left+15 center", at: "right center" }
            }).triggerHandler('mouseover');
        }
    });
});

Demo: Fiddle

As @roasted suggested you can use the open method instead of triggering mouseover.

Instead of .triggerHandler('mouseover'); use tooltip('open');