Reputation: 43
I have a users card list, my task is:
Clicking "undo" button: will restore the last card that was deleted (use array)
Question 1: How to make array from cards list I have displayed ? Question 2: How to restore the last card that was deleted? (IF 2 cards are removed, "undo" button will to restore card one by one)
Link to codepen here https://codepen.io/MarinaShumeiko/pen/Nbeqew?editors=1010
var root = 'https://jsonplaceholder.typicode.com';
var notificationMessage = "Oops, there are no more user cards to display";
var userIndex = 0;
var undoBtn = $("#button")
var $clearBtn = $("#clear");
var $contentArea = $("#content");
var cardTemplate = '<div class="card" data-id="{id}"><div class="title"><div class="image"></div><div class="name">{name}</div><button onclick="removeUser({postid})" class="close"></button></div><div class="description">{body}<a href="mailto:" class="email">{email}</a></div></div>';
// - Load all the card at once, when screen load
$(function() {
$contentArea.append(renderUser);
});
// Make array from usercards
var $cardDiv = $(".card");
var usersCardArray = $cardDiv.toArray(); // return usersCardArray.length = 0 :(
//remove all card at once
$clearBtn.click(clearUsers);
function clearUsers () {
$contentArea.empty();
userIndex = 0;
}
//remove one card
$('.card .close').on('click', removeUser);
function removeUser(postId) {
$('[data-id="' + postId + '"]').remove();
}
// get user data
function getUser () {
return $.ajax({ url: root + '/posts/1/comments', method: 'GET' });
}
function renderUser() {
getUser().then(function (user) {
for (var i = 0; i = user.length; i++) {
var card = cardTemplate
.replace('{id}', user[userIndex].id)
.replace('{postid}', user[userIndex].id)
.replace('{name}', user[userIndex].name)
.replace('{body}', user[userIndex].body)
.replace('{email}', user[userIndex].email);
$contentArea.append(card);
userIndex++;
}
})
}
Upvotes: 2
Views: 1155
Reputation: 834
Since you don't manipulate any actual data, only the view itself - you can add class .hidden
on delete card, and remove this class on undo.
To keep track on deleted users I added array var deletedUsers =[]
. Each time you delete a user, add its id to array and hide it from view by adding class hidden
.
On undo - pop the user id from deletedUsers
, and remove class hidden
from this user's card
https://codepen.io/anon/pen/PbXxrB
Upvotes: 5