I am currently working on a project to create a dynamic to-do list. Each task is represented as an object that generates the necessary HTML code and adds itself to a div
container. The variable listItemCode
holds all the required HTML code for each list item, including the code to create a remove button within each item's div
.
While everything seems to be functioning correctly in this JSFiddle, there is an issue with the top-most item (labeled "Relax") not removing itself when its remove button is clicked.
If you add a new list item using the input fields and submit button, the last item becomes unremovable while the second-top-most item can still be removed.
I have been struggling to pinpoint and resolve this bug.
// Array to store all tasks as objects
var tasks = [];
// Make the list sortable
$("#mainlist").sortable();
// Task Constructor function
var Task = function (title, description) {
this.title = title;
this.description = description;
var listItemCode = "<div class='listItem'>" + "<input class='title' name='title' onClick='this.select();' placeholder='Title' value='" + title + "'><br>" + "<input class='description' name='description' onClick='this.select();' placeholder='Description' value='" + description + "'>" + "<div class='date'>" + date() + "</div>" + "<div class='removeButton'>X</div>" + "</div>";
$(".removeButton").click(function() {
listItemCode = "";
$(this).parent(".listItem").fadeTo(200, 0).slideUp('fast', function() { $(this).remove(); });
});
// Add current task to the tasks array
tasks.push(this);
// Display task in the browser
$("#mainlist").prepend(listItemCode);
};
// Add Placeholder Tasks for Design Purposes
addPlaceholderTasks(true);
// User Adds a New Task
$("input[name=submit]").click(function () {
var newTask = new Task($("input[name=title]").val(),
$("input[name=description]").val());
});
// Retrieve and format the current date
function date() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
var hour = today.getHours();
var minute = today.getMinutes();
var currentDateTime = dd + "." + mm + "." + yyyy + " at " + hour + ":" + minute;
return currentDateTime;
}
// Placeholder Tasks for Design Purposes
function addPlaceholderTasks(x) {
if (x === true) {
var task1 = new Task("Milk the cow", "You know she wants it.");
var task2 = new Task("Get funky", "Boogie on down to the club.");
var task3 = new Task("Freakify", "Get your freak on.");
var task4 = new Task("Relax", "Time to get jiggy with it.");
}
}