Редактировать задачу в todo list js
Всем привет, помогите тут плиз, я постоянно дорабатываю тудушку и вот мне нужно сделать возможность, чтобы можно было редактировать таск, ну у меня почему-то не получается, я пытался по разному создавать из разных источников, но не один не помогал, тут скорее всего я что-то не так делал, заранее спасибо, вот код:
//1) создаю три главных переменных, которые подключаются к основным html функционалом туду листа
const addTask = document.getElementById('add-task');
const inputTask = document.getElementById('task-input');
const allTasks = document.querySelector('.all-tasks');
const delAll = document.getElementById('delete-all-tasks')
let tasks = [];
let todoTasks = [];
/*
if (!localStorage.tasks) {
tasks = []
} else {
tasks = JSON.parse(localStorage.getItem('tasks'))
}*/
//2) создаю функцию-конструктор, которая поможет создать много однотипных объектов
function Task(task) {
this.task = task;
this.completed = false;
}
//6) создаю функцию, где будет сам таск
function createTask(description, index) {
return `
<div class="create-task ${description.completed ? 'checked' : ''}">
<div class="task">${description.task}</div>
<div class="action">
<input onclick="completedTask(${index})" class="complete" type="checkbox"
${description.completed ? 'checked' : ''}>
<span onclick="editTask(${index})" class="btn-edit"><i class="fa-solid fa-pen-to-square"></i></span>
<span onclick="deletedTask(${index})" class="delete"><i class="fa-solid fa-trash"></i></span>
</div>
</div>
`
}
//9) создаю функцию, которая будет фильтровать завершенные таски и опускать их вниз
function filterTasks() {
const activeTasks = tasks.length && tasks.filter(item => item.completed === false);
const completedTasks = tasks.length && tasks.filter(item => item.completed === true);
tasks = [...activeTasks, ...completedTasks];
}
//5) создаю функцию, в которой таски будут выводится на странице
function showTasks() {
allTasks.innerHTML = "";
if (tasks.length === 0) {
delAll.classList.add("hide");
} else {
delAll.classList.remove("hide");
}
if (tasks.length > 0) {
filterTasks();
tasks.forEach((item, index) => {
allTasks.innerHTML += createTask(item, index)
});
todoTasks = document.querySelectorAll('.create-task');
}
}
showTasks();
//4) создаю функцию, где я буду обращаться к locale storage, чтобы хранить там таски
function storage() {
//localStorage.setItem('tasks', JSON.stringify(tasks))
}
//7) создаю функцию, которая будет отвечать за завершения таска
function completedTask(index) {
tasks[index].completed = !tasks[index].completed;
if (tasks[index].completed) {
todoTasks[index].classList.add('checked')
setTimeout(() => {
alertify.success('Task done!')
}, 150)
} else {
todoTasks[index].classList.remove('checked')
setTimeout(() => {
alertify.warning('Task not done!')
}, 150)
}
storage();
showTasks();
}
//8) создаю функцию, которая будет отвечать за удаления таска
function deletedTask(index) {
todoTasks[index].classList.add('deleted')
setTimeout(() => {
tasks.splice(index, 1);
storage();
showTasks();
}, 500)
setTimeout(() => {
alertify.success('Task deleted!')
}, 550)
}
function editTask() {
}
//3) создаю нажатие на кнопку добавить новый таск
addTask.addEventListener("click", () => {
if (inputTask.value === '') {
alertify.error('Enter a task!')
} else {
setTimeout(() => {
alertify.success('Task added!')
}, 100)
tasks.push(new Task(inputTask.value));
}
storage();
showTasks();
inputTask.value = '';
});
//10 создаю нажатие на кнопку, которая удаляет все таски
delAll.addEventListener("click", () => {
setTimeout(() => {
alertify.success('All tasks deleted!')
}, 100)
tasks = [];
storage();
showTasks();
});
body {
background: #EEEEEE;
}
h1 {
font-size: 50px;
text-align: center;
font-family: cursive;
}
h2 {
font-size: 25px;
text-align: center;
font-family: cursive;
}
.todo {
display: flex;
flex-flow: column;
justify-content: center;
align-items: center;
width: 100%;
}
.add-todo {
display: flex;
width: 500px;
height: 40px;
align-items: center;
background-color: #212121;
border-radius: 20px;
padding: 10px;
}
.input-task {
width: 80%;
}
.input-task input {
width: 425px;
height: 28px;
border-radius: 20px;
font-family: cursive;
font-size: 15px;
}
.add-task-button {
width: 95px;
display: flex;
justify-content: flex-end;
color: aqua;
}
.add-task-button button {
width: 50px;
height: 35px;
font-size: 22px;
background-color: aqua;
color: black;
border-radius: 10px;
cursor: pointer;
}
.add-task-button button:hover {
background-color: lightgreen;
}
.create-task {
display: flex;
width: 500px;
height: 50px;
background-color: lightgreen;
border-radius: 10px;
border: 2px solid black;
margin-bottom: 15px;
padding: 10px;
font-family: cursive;
}
.create-task.checked {
background-color: grey;
opacity: 0.5;
text-decoration: line-through;
}
.create-task.deleted {
animation: 1s slidein;
}
.create-task.hide {
display: none;
}
@keyframes slidein {
from {
transform: translateX(0%);
}
to {
transform: translateX(100%);
}
}
.task {
width: 80%;
display: flex;
align-items: center;
color: black;
}
.action {
width: 20%;
display: flex;
align-items: center;
justify-content: flex-end;
}
.action input {
width: 25px;
height: 25px;
cursor: pointer;
}
input[type='checkbox'] {
margin: 10px;
border-radius: 50px;
}
.action span {
color: #B71C1C;
cursor: pointer;
height: 25px;
font-size: 25px;
margin-bottom: 14px;
}
.action span:hover {
color: darkred;
}
.action span.btn-edit {
color: #1A237E;
padding-right: 8px;
}
.action span.btn-edit:hover {
color: darkcyan;
}
.del-all-tasks-button button {
background-color: #B71C1C;
color: black;
cursor: pointer;
font-family: cursive;
height: 30px;
border-radius: 5px;
margin: 10px;
/* user-select: none;
opacity: 0.6;
pointer-events: none;
*/
}
.del-all-tasks-button button:hover {
background-color: darkred;
}
.del-all-tasks-button button.hide {
display: none;
}
.input-edit {
margin: 0;
font-size: 18px;
line-height: 18px;
height: 18px;
padding: 10px;
border: 1px solid #ddd;
background: #fff;
border-radius: 6px;
font-family: Lato, sans-serif;
color: #888;
display: none;
}
.input-edit.edit {
padding: 5px;
margin-right: 150px;
display: none;
}
.active {
display: block;
}
.noactive {
display: none;
}
input-edit:focus {
color: #333;
}
.txt {
font-family: cursive;
margin-top: 60px;
margin-right: 40px;
font-size: 18px;
}
/* .btn-edit {
background-color: #00537e;
margin-right: 10px;
}
.btn-edit:hover {
background-color: #033953;
} */
<link href="//cdn.jsdelivr.net/npm/[email protected]/build/css/alertify.min.css" rel="stylesheet"/>
<link href="//cdn.jsdelivr.net/npm/[email protected]/build/css/themes/default.min.css" rel="stylesheet"/>
<script src="//cdn.jsdelivr.net/npm/[email protected]/build/alertify.min.js"></script>
<h1>ToDo List</h1>
<div class="todo">
<div class="add-todo">
<div class="input-task">
<input type="text" id="task-input" placeholder="What needs to be done today?">
</div>
<div class="add-task-button">
<button id="add-task"><i class="fas fa-plus"></i></button>
</div>
</div>
</br>
<h2 style>Tasks for the day:</h2>
<div class="all-tasks"></div>
<div class="del-all-tasks-button">
<button id="delete-all-tasks">Clear All</button>
</div>
</div>
Ответы (1 шт):
Автор решения: De.Minov
→ Ссылка
Редактирование таска происходит следующим образом:
При нажатии на кнопку "редактировать", вместо теста таска появляется инпут с этим текстом, который можно изменить.
При повторном нажатии на кнопку "редактировать", значение с инпута заменяется в массиве и вместо инпута появляется текст.
//1) создаю три главных переменных, которые подключаются к основным html функционалом туду листа
const addTask = document.getElementById('add-task');
const inputTask = document.getElementById('task-input');
const allTasks = document.querySelector('.all-tasks');
const delAll = document.getElementById('delete-all-tasks')
let tasks = [];
let todoTasks = [];
/*
if (!localStorage.tasks) {
tasks = []
} else {
tasks = JSON.parse(localStorage.getItem('tasks'))
}*/
//2) создаю функцию-конструктор, которая поможет создать много однотипных объектов
function Task(task) {
this.task = task;
this.completed = false;
}
//6) создаю функцию, где будет сам таск
function createTask(description, index) {
return `
<div class="create-task ${description.completed ? 'checked' : ''}">
<div class="task">${description.task}</div>
<div class="action">
<input onclick="completedTask(${index})" class="complete" type="checkbox"
${description.completed ? 'checked' : ''}>
<span onclick="editTask(${index})" class="btn-edit"><i class="fa-solid fa-pen-to-square"></i></span>
<span onclick="deletedTask(${index})" class="delete"><i class="fa-solid fa-trash"></i></span>
</div>
</div>
`
}
//9) создаю функцию, которая будет фильтровать завершенные таски и опускать их вниз
function filterTasks() {
const activeTasks = tasks.length && tasks.filter(item => item.completed === false);
const completedTasks = tasks.length && tasks.filter(item => item.completed === true);
tasks = [...activeTasks, ...completedTasks];
}
//5) создаю функцию, в которой таски будут выводится на странице
function showTasks() {
allTasks.innerHTML = "";
if (tasks.length === 0) {
delAll.classList.add("hide");
} else {
delAll.classList.remove("hide");
}
if (tasks.length > 0) {
filterTasks();
tasks.forEach((item, index) => {
allTasks.innerHTML += createTask(item, index)
});
todoTasks = document.querySelectorAll('.create-task');
}
}
showTasks();
//4) создаю функцию, где я буду обращаться к locale storage, чтобы хранить там таски
function storage() {
//localStorage.setItem('tasks', JSON.stringify(tasks))
}
//7) создаю функцию, которая будет отвечать за завершения таска
function completedTask(index) {
tasks[index].completed = !tasks[index].completed;
if (tasks[index].completed) {
todoTasks[index].classList.add('checked')
setTimeout(() => {
alertify.success('Task done!')
}, 150)
} else {
todoTasks[index].classList.remove('checked')
setTimeout(() => {
alertify.warning('Task not done!')
}, 150)
}
storage();
showTasks();
}
//8) создаю функцию, которая будет отвечать за удаления таска
function deletedTask(index) {
todoTasks[index].classList.add('deleted')
setTimeout(() => {
tasks.splice(index, 1);
storage();
showTasks();
}, 500)
setTimeout(() => {
alertify.success('Task deleted!')
}, 550)
}
// Редактирование таска
function editTask(index) {
let curTask = todoTasks[index]; // выбранный таск
if(!curTask.classList.contains('edit')) { // При первом нажатии на кнопку редактирования, начинаем редактировать.
curTask.classList.add('edit'); // Добавляем класс
curTask.querySelector('.task').innerHTML = `<input type="test" value="${tasks[index].task}">`; // Вместо задачи добавляем инпут с редактированием
} else { // При втором нажатии, когда класс `.edit` есть, мы сохраним
let newTask = curTask.querySelector('.task > input').value;
tasks[index].task = newTask;
curTask.querySelector('.task').innerText = newTask;
curTask.classList.remove('edit');
// storage();
}
}
//3) создаю нажатие на кнопку добавить новый таск
addTask.addEventListener("click", () => {
if (inputTask.value === '') {
alertify.error('Enter a task!')
} else {
setTimeout(() => {
alertify.success('Task added!')
}, 100)
tasks.push(new Task(inputTask.value));
}
storage();
showTasks();
inputTask.value = '';
});
//10 создаю нажатие на кнопку, которая удаляет все таски
delAll.addEventListener("click", () => {
setTimeout(() => {
alertify.success('All tasks deleted!')
}, 100)
tasks = [];
storage();
showTasks();
});
body {
background: #EEEEEE;
}
h1 {
font-size: 50px;
text-align: center;
font-family: cursive;
}
h2 {
font-size: 25px;
text-align: center;
font-family: cursive;
}
.todo {
display: flex;
flex-flow: column;
justify-content: center;
align-items: center;
width: 100%;
}
.add-todo {
display: flex;
width: 500px;
height: 40px;
align-items: center;
background-color: #212121;
border-radius: 20px;
padding: 10px;
}
.input-task {
width: 80%;
}
.input-task input {
width: 425px;
height: 28px;
border-radius: 20px;
font-family: cursive;
font-size: 15px;
}
.add-task-button {
width: 95px;
display: flex;
justify-content: flex-end;
color: aqua;
}
.add-task-button button {
width: 50px;
height: 35px;
font-size: 22px;
background-color: aqua;
color: black;
border-radius: 10px;
cursor: pointer;
}
.add-task-button button:hover {
background-color: lightgreen;
}
.create-task {
display: flex;
width: 500px;
height: 50px;
background-color: lightgreen;
border-radius: 10px;
border: 2px solid black;
margin-bottom: 15px;
padding: 10px;
font-family: cursive;
}
.create-task.edit {
background-color: #90eee1;
border-color: #005b64;
}
.create-task.edit .btn-edit {
background: green;
}
.create-task.checked {
background-color: grey;
opacity: 0.5;
text-decoration: line-through;
}
.create-task.deleted {
animation: 1s slidein;
}
.create-task.hide {
display: none;
}
@keyframes slidein {
from {
transform: translateX(0%);
}
to {
transform: translateX(100%);
}
}
.task {
width: 80%;
display: flex;
align-items: center;
color: black;
}
.action {
width: 20%;
display: flex;
align-items: center;
justify-content: flex-end;
}
.action input {
width: 25px;
height: 25px;
cursor: pointer;
}
input[type='checkbox'] {
margin: 10px;
border-radius: 50px;
}
.action span {
color: #B71C1C;
cursor: pointer;
height: 25px;
font-size: 25px;
margin-bottom: 14px;
}
.action span:hover {
color: darkred;
}
.action span.btn-edit {
color: #1A237E;
padding-right: 8px;
}
.action span.btn-edit:hover {
color: darkcyan;
}
.del-all-tasks-button button {
background-color: #B71C1C;
color: black;
cursor: pointer;
font-family: cursive;
height: 30px;
border-radius: 5px;
margin: 10px;
/* user-select: none;
opacity: 0.6;
pointer-events: none;
*/
}
.del-all-tasks-button button:hover {
background-color: darkred;
}
.del-all-tasks-button button.hide {
display: none;
}
.input-edit {
margin: 0;
font-size: 18px;
line-height: 18px;
height: 18px;
padding: 10px;
border: 1px solid #ddd;
background: #fff;
border-radius: 6px;
font-family: Lato, sans-serif;
color: #888;
display: none;
}
.input-edit.edit {
padding: 5px;
margin-right: 150px;
display: none;
}
.active {
display: block;
}
.noactive {
display: none;
}
input-edit:focus {
color: #333;
}
.txt {
font-family: cursive;
margin-top: 60px;
margin-right: 40px;
font-size: 18px;
}
.btn-edit {
background-color: #00537e;
margin-right: 10px;
}
.btn-edit:hover {
background-color: #033953;
}
<link href="//cdn.jsdelivr.net/npm/[email protected]/build/css/alertify.min.css" rel="stylesheet" />
<link href="//cdn.jsdelivr.net/npm/[email protected]/build/css/themes/default.min.css" rel="stylesheet" />
<script src="//cdn.jsdelivr.net/npm/[email protected]/build/alertify.min.js"></script>
<h1>ToDo List</h1>
<div class="todo">
<div class="add-todo">
<div class="input-task">
<input type="text" id="task-input" placeholder="What needs to be done today?">
</div>
<div class="add-task-button">
<button id="add-task"><i class="fas fa-plus"></i></button>
</div>
</div>
</br>
<h2 style>Tasks for the day:</h2>
<div class="all-tasks"></div>
<div class="del-all-tasks-button">
<button id="delete-all-tasks">Clear All</button>
</div>
</div>