views:

99

answers:

1

Hello,

i have the following code example (see below), my problem is that the tooltip doesn't show the "old" text after i go away with the cursor - any ideas? Regards

<style type="text/css">
#tooltip {
    position: absolute;
    background: #FFF;
    display: none;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"&gt;&lt;/script&gt;
<script type="text/javascript">
$(document).ready(function(){
    $('body').append('<div id="tooltip"></div>');
    var tt = $('#tooltip');
    $('a.tooltip').each(function(){
        $(this).data('title', this.title).attr('title', '');
    }).hover(function(){
        var t = $(this), o = t.offset();
        tt.html(t.data('title')).css({top: o.top, left: o.left}).fadeIn('fast');        
    },
    function(){
        tt.css({display: 'none'});
    });
});
</script>
</head>
<body>

    <a href="#" class="tooltip" title="VeryLongTextMoreTextVeryLongText">VeryLongText...VeryLongText</a> 
A: 

The problem is the mouse enter the <a> but then it's on the tooltip element, so you need to split the hover, like this:

$('body').append('<div id="tooltip"></div>');
var tt = $('#tooltip');
$('a.tooltip').each(function(){
    $(this).data('title', this.title).attr('title', '');
}).mouseenter(function(){
    var t = $(this), o = t.offset();
    tt.html(t.data('title')).css({top: o.top, left: o.left}).fadeIn('fast');
});
tt.mouseleave(function() {
  $(this).stop().hide();
});

You can give it a try here, since the mouse over occurs on the <a>, add the .mouseeenter() to it. But, since you're then over the #tooltip on top of the <a>, to hide it you need the .mouseleave() on the #tooltip itself.

What's happening currently is it starts to .fadeIn(), but as soon as it does so the mouseleave event happens (since #tooltip isn't a child), so the display: none; is triggered (you can use .hide() here). The display:none; does happen, but the next interval of the fade just reverses it, so you end up with a faded-in element. To prevent that in the mouseleave handler above, we've added .stop() to stop further fading for this hover.

Nick Craver
Thanks Nick :) - Works Fine Now
Jens
@Jens - Welcome :) Be sure to accept answers on this and future questions via the check beside the one that helped, it'll help you get more responses as you go (high accept rate == appealing). Last but not least, welcome to SO!
Nick Craver