Pulling value from alt tag - need it to change on click Jquery
-
09-12-2019 - |
Question
Ok - so I've made a little image gallery - basically when you click a thumbnail, it pulls in the title from the alt tag - puts it in a div to display below the image as the title, and displays the image as a fullscreen bg
What I'm trying to do is have this title display when the page loads - and when you click, remove the existing value and replace it with the new one
Currently the title isn't displaying on page load, when you click it - it shows the title as desired, but when you click another image it doesn't remove this title
Heres my existing code
<ul id="horses">
<li><a class="clicker" rel="drawings-bg"><img src="/assets/img/portfolio/horse.jpg" alt="horse" /></a></li>
<li><a class="clicker" rel="contact-bg"><img src="/assets/img/portfolio/dogs.jpg" alt="dogs" /></a></li>
<li><a class="clicker" rel="drawings-bg"><img src="/assets/img/portfolio/horse.jpg" alt="horse" /></a></li>
</ul>
Jquery
$(document).ready(function() {
var imginfo = $('.imgtitle');
$("ul#horses li img").click(function() {
if(imginfo) $(imginfo).siblings('.imgtitle').remove();
$(this).parent().append("<div class=imgtitle>" + $(this).attr("alt") + "</div>");
});
});
Thanks in advance
Solution
Most of it seems to work:
This line has a problem:
if(imginfo) $(imginfo).siblings('.imgtitle').remove();
jQuery instances are always truthy, so that line will always run. Ignoring that, though, shouldn't it be more like this?
$(document).ready(function() {
var imginfo = $('.imgtitle');
$("ul#horses li img").click(function() {
$('ul#horses li .imgtitle').remove();
$(this).parent().append(
"<div class=imgtitle>" + $(this).attr("alt") + "</div>"
);
});
});
...if you're trying to remove the other titles when displaying a new one: http://jsbin.com/iqugih
OTHER TIPS
try this:
$("ul#horses li img").click(function() {
var i = $(this);
var imageTitle = i.parent().find('.imgtitle');
if(null === imageTitle || imageTitle.length == 0) {
imageTitle = $('<div/>').addClass('imgtitle');
i.parent().append(imageTitle);
}
imageTitle.html(i.attr('alt'));
});