display alt tag for image using this - jquery
A client wants the alt tag text to appear when hovered (and can't be convinced it should be title, alas). This is as far as I got, but I need only the hovered img's alt tag to display, rather than all of them. I tried removing 'each' but it broke (I know I'm not very good at this). How do I fix it:
$("ul.thumb li img").hover(function() {
$(this).each(function(i, ele) {
$("li").append("<div class=alt>"+$(ele).attr("alt")+"</div>");
$(this).mouseleave(function(event){
$(".alt").css('display','none');
});
});
});
Here it is in a开发者_如何学编程 fiddle
$("ul.thumb li img").each(function() {
$(this).parent('li').append($("<span/>").text($(this).attr("alt")).hide());
}).hover(function(){
$(this).parent('li').children('span').show();
},function(){
$(this).parent('li').children('span').hide();
});
DEMO
You can do it in two steps:
// create the divs
$("ul.thumb li img").each(function() {
$('<div />', {
class: 'alt',
text: $(this).attr("alt")
}).appendTo($(this).parent());
});
// toggle the divs visibility
$("ul.thumb li img").hover(function() {
$(this).parent().children('.alt').toggle();
});
// OR attach the handler to the li element instead:
$("ul.thumb li").hover(function() {
$(this).children('.alt').toggle();
});
DEMO
You don't need the .each()
, and you can handle the mouseleave
as the second parameter to .hover()
:
$("ul.thumb li img").hover(function() {
console.log(this);
$(this).parent().append("<div class=alt>" + $(this).attr("alt") + "</div>");
}, function() {
$(this).siblings('.alt').remove();
});
Working demo at http://jsfiddle.net/alnitak/dPVCN/
NB: I'm remove the .alt
div altogether on mouseout, since otherwise it would keep appending the alt text over and over again.
A better solution might be to pre-create all of the alt divs, and then just .show()
or .hide()
them as appropriate.
TheSuperTramp's solution is the best approach, but I've tweaked it slightly to improve performance.
$('img', 'ul').each(function() { $(this).parent().append('<div style="display:none">' + this.alt + '</div>'); }).bind({ mouseenter: function() { $(this).siblings('div').show(); }, mouseleave: function() { $(this).siblings('div').hide(); } });
Demo: http://jsfiddle.net/5dxhC/1/
There are two problems:
- You are appending the
div
to allli
elements instead of just the current one (see @cdeszaq's answer) - You are hiding the newly added
div
onmouseleave
, making all future.alt
elements hidden. You should use.remove()
instead of a css property onmouseout
精彩评论