Reputation: 109
The undo button only appends the last detached.item
and does not allow for appending detached items beyond the last removed. The goal is to remove as many items as I wish and have them restored in succession with each click of the undo button.
$(document).ready(function() {
var cacheDom = "";
$('.remove').click(function() {
if ($('.item').length > 0) {
cacheDom = $('.item');
$(this).closest('.item').detach();
}
});
$('#undo').click(function() {
$('.list').append(cacheDom);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list">
<div class="item">
Item 1
<button class='remove'>Remove</button>
</div>
<div class="item">
Item 2
<button class='remove'>Remove</button>
</div>
<div class="item">
Item 3
<button class='remove'>Remove</button>
</div>
</div>
<button id='undo'>Undo</button>
Upvotes: 0
Views: 42
Reputation: 24965
You can keep an array of the elements removed, and restore them, beginning with the first element in the array.
$(document).ready(function() {
var removedItems = [];
$('.remove').click(function() {
var removeItem = $(this).closest('.item').detach();
removedItems.push(removeItem);
});
$('#undo').click(function() {
if (removedItems.length) {
var restoreItem = removedItems.shift();
$('.list').append(restoreItem);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list">
<div class="item">
Item 1
<button class='remove'>Remove</button>
</div>
<div class="item">
Item 2
<button class='remove'>Remove</button>
</div>
<div class="item">
Item 3
<button class='remove'>Remove</button>
</div>
</div>
<button id='undo'>Undo</button>
Upvotes: 1