user1459482
user1459482

Reputation: 17

Hover twice for ajax to load

This works, but when I hover the first time, nothing loads. When I mouse off then back on, ajax has loaded. I want ajax to load on the first hover.

index.html

<span title="" id="test" class="tooltip"></span>

tooltip.html

<span id="test">this is ajax</span>

jquery

$('.tooltip').hover(function () {
    var id = $(this).attr('id');
    $.get('tooltip.html #'+id, function(data) {
        $('#'+id).attr('title', data);
    });
});

Upvotes: 1

Views: 466

Answers (3)

OptimusCrime
OptimusCrime

Reputation: 14863

As pointed out earier, the problem is that the browser displays the inbuilt title as soon as you hover the element, and ajax use some time to load the content and append it.

I would advice you to use one of the MANY tooltip-plugins out there: https://www.google.com/search?q=tooltip+jquery+plugin

I've had some great experience with qTip. Easy to set up and easy to restyle.

Upvotes: 0

will
will

Reputation: 4575

This is because the first time you hover (which is actually the mouseenter event) the ajax function loads the data and changes the title, but the mouseenter event has already fired and your tooltip is already open so it's too late.

Your best bet is to directly alter the tooltip rather than change the title of the original element.

What you should actually do is change both and alter your hover function to check for a title so that next time the hover occurs you don't need to load the information again, rather refer to the title you've already populated.

Hope that helps :)

Upvotes: 1

Evan Davis
Evan Davis

Reputation: 36592

Looks like you are relying on the browser's inbuilt tooltips (showing the title on hover.) That tooltip is likely triggered by the mouseover event, meaning that after you've dynamically added the title, you need another mouseover event to actually trigger the tooltip. Seems it's working as designed.

Upvotes: 1

Related Questions