'jQuery clicked element AppendTo another Div in a each function
I will build a Stacked Images Carousel like this https://www.jqueryscript.net/demo/3D-Card-Carousel-Rotator-With-jQuery-CSS3/
The JS Code (https://www.jqueryscript.net/rotator/3D-Card-Carousel-Rotator-With-jQuery-CSS3.html) is build to use the Carousel just one time in a page.
But I will use it more than one time on the same page. So I have to rewrite the script. I try this with jquery and an each click function. My CSS is working well but i have trouble to appendTo the clicked Element to my wrapper div.
My markup
<div class="stackimages-items">
<div class="stackimages-item">
<img src="image-001.jpg">
</div>
<div class="stackimages-item">
<img src="image-002.jpg">
</div>
<div class="stackimages-item">
<img src="image-003.jpg">
</div>
</div>
This is how it will work, but only when i will use the Carousel one time in a page.
$('.stackimages-item').click(function() {
$('.stackimages-item:first-child').fadeOut(400, 'swing', function() {
$('.stackimages-item:first-child').appendTo('.stackimages-items').hide();
}).fadeIn(400, 'swing');
});
And this is what I try to use it more than one time in a page. But it will not append it to my wrapper (stackimages-items).
$('.stackimages-item').click(function(e) {
$(this).find(':first-child').fadeOut(400, 'swing', function() {
$(this).appendTo('.stackimages-items').hide();
}).fadeIn(400, 'swing');
});
What did i wrong? Thanks for your help in advance.
Solution 1:[1]
Your attempt with $(this).find(':first-child')
would have had an original equivalent of
$(".stackimages-item :first-child")
The equivalent of .stackimages-item:first-child is
$(this).filter(':first-child')
//or
$(this).first()
Secondly: $(this).appendTo('.stackimages-items') will append to all .stackimages-items, likely duplicating your image across each stack.
Instead you'll want to use:
$(this).appendTo($(this).closest('.stackimages-items')).hide();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | freedomn-m |
