I'm trying to use this piece of code to reveal image captions of multiple images using a single link on a page. I've updated the code from a mouseenter function to a click function and added a new caption toggle that should reveal any captions associated with each image.
JS
$(function () {
$(".thumb").click(function () { //replaced to click
var $t = $(this);
var $d = $("<div>");
$d.addClass("desc").text($t.attr("alt")).css({
width: $t.width(),
height: $t.height() - 20,
top: $t.position().top
});
$(this).find('.caption').toggleClasss('hidden '); //added caption toggle
$t.after($d).fadeTo("fast", 0.3);
$d.click(function () { //replaced to click
$(this).fadeOut("fast", 0, function () {
$(this).remove();
}).siblings("img.thumb").fadeTo("fast", 1.0);
});
});
});
HTML
<img class="thumb" src="http://t3.gstatic.com/images?q=tbn:ANd9GcQidl6KX2jRWNeCA6jT_TjWG7NlI3aRiB_AcDsA9Y5owS2cr9G6" alt="Nice painting">
<a class="caption" href="#">Click Me!</a>
CSS
.thumb {
cursor: pointer;
}
.desc {
cursor: pointer;
position: absolute;
color: #000;
text-shadow: 0 0 5px 2px #fff;
z-index: 1;
text-align: center;
padding: 10px 0;
}
.hidden {
display:none;
}
Here's the code in action. http://jsfiddle.net/hJMXa/
I'm pretty new to Jquery and I've sort of exhausted all the options that I could think of. Any suggestions??
Here is what I imagine your trying to achieve:
var img = $('img'),
div = $(img.data('target')),
caption = img.attr('caption'),
someLink = $('a');
someLink.one('click', function() {
div.append(caption).hide().slideDown();
$(this).remove();
return false;
});
UPDATE
captionToggle.init({
container: '.img_caption_container',
loader: 'div.loader',
link: 'a.link',
slideDownFx: 'slideDown',
slideUpFx: 'slideUp',
showText: 'Hide Caption!',
hideText: 'Show Caption!'
});
var captionToggle = {
init: function(config) {
$.each($(config.container), function() {
var $this = $(this),
$caption = $this.children('img').eq(0).attr('caption'),
$loader = $this.children(config.loader).hide(),
$link = $this.children(config.link);
$link.on('click', function() {
if ( $loader.text().length == 0 ) $loader.append($caption);
if ( $(this).text() == 'Show Caption!' ) {
$loader[config.slideDownFx]();
$(this).text(config.showText);
} else {
$(this).text(config.hideText);
$loader[config.slideUpFx]();
}
return false;
});
});
}
}