开发者

jQuery: toggle text on hover over image?

In jQuery, how can I get text to toggle when the user hovers over an image?

I have code that changes the text when the user hovers:

# HTML
<table id="support-people">
<tr>
<td><img data-bio="Bio 1" src="person1.jpg" alt="Person 1"/></td>
<td><img data-bio="Bio 2" src="person2.jpg" alt="Person 2"/></td>
</tr>
<tr><td colspan="2">
<p id="support-person-description">Default text</p>
</td></tr></tabl开发者_高级运维e>

# JS
$('#support-people img').hover(function(){
    $('#support-person-description').text(this.getAttribute("data-bio"));
});

But when the user moves away, the text stays the same - is there a neat way I can get it to toggle back to the original, default text?

Thanks.


Use the two functions of hover (first for mouse over, second for mouse out) then in the first save the oldtext as data on the element. Then read this value and set it in the second function:

$('#support-people img').hover(function(){
    var desc = $('#support-person-description');
    desc.data('oldtext', desc.text()).text(this.getAttribute("data-bio"));
}, function() {
    var desc = $('#support-person-description');
    desc.text(desc.data('oldtext'));
});


try :

$('#support-people img').hover(function(){
    var $elem = $('#support-person-description');
    $elem.data('oldText', $elem.text()).text(this.getAttribute("data-bio")); // Add text on mouse hover
},function(){
    var $elem = $('#support-person-description');
    $elem.text($elem.data('oldText')); // Return to default
});


Change your javascript to the following.

$('#support-people img').hover(function(){
    $('#support-person-description').text(this.getAttribute("data-bio"));
}, function(){
    $('#support-person-description').text('Default text');
});


You can write onMouseOver and onMouseOut functions in the same call http://api.jquery.com/hover/


the .hover() method requires TWO parameters. On for what happens when hovering and one for when not hovering. Your code only has the instruction to display the element. You are missing the instruction to remove it again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜