I’m trying to make a simple gallery and can’t figure out what is wrong with my jQuery syntax.
When the user clicks a thumbnail (one of the first three list items), I want to clone() the image and caption, and paste it into li.expand (the full-size image).
The first two lines of my jQuery function are working (i.e. the “selected” class) but the last two lines don’t seem to be doing anything. Am I using $(this) wrong?
HTML
<ul class="gallery2">
<li>
<img src="img/1.jpg" />
<p>Caption 1</p>
</li>
<li>
<img src="img/2.jpg" />
<p>Caption 2</p>
</li>
<li>
<img src="img/3.jpg" />
<p>Caption 3</p>
</li>
<li class="expand">
<!-- This space will be filled with whatever thumbnail is selected -->
</li>
</ul>
jQuery
$(".gallery2 li").click(function () {
$(".gallery2 li").removeClass("selected");
$(this).addClass("selected");
$(".gallery2 li.expand").html().remove();
$(this).html().clone().appendTo(".gallery2 li.expand");
});
html()returns a string, not a jQuery object. Perhaps you mean to usechildren()? Additionally, rather than use.children().remove(), you can useempty(). With those changes:You might also consider using
siblings()to select sibling elements:And if we’re going to go to all that trouble, why not make it more generic by turning it into a plugin?
Then it’s this simple to make a gallery:
Try it on JSFiddle.