JSFiddle - React, Tailwind, and code Playground
by Boba Poshtar
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ToDo</title>
</head>
<style>
.custom {
color: red;
display: flex;
margin-left: 20px;
flex-direction: column;
}
.container {
display: flex;
flex-direction: column;
row-gap: 10px;
}
.todo {
color: green;
margin-left: 20px;
cursor: pointer;
font-size: 18px;
padding: 5px;
border: 1px solid black;
width: 120px;
}
.todo:hover {
color: red;
}
button {
margin-top: 20px;
margin-left: 20px;
height: 20px;
}
body {
display: flex;
}
</style>
<body>
<div class="todo-container">
</div>
<button>Add todo</button>
</body>
</html>
JavaScript
const todoContainer = document.querySelector('.todo-container');
const todos = [
{ text: 'Todo 1', id: '1' },
{ text: 'Todo 2', id: '2' },
{ text: 'Todo 3', id: '3' }
];
document.querySelector('button').addEventListener('click', addNewTodo);
render();
function addNewTodo() {
todos.push({
id: random(),
text: 'Todo ' + random()
});
render();
function random() {
return Math.floor(Math.random() * 1000000);
}
}
function render() {
todoContainer.replaceChildren(createTodoWrapper());
}
function createTodoWrapper() {
const wrapper = document.createElement('div');
wrapper.className = 'container';
todos.forEach(todo => wrapper.appendChild(createTodo(todo.text, todo.id)));
return wrapper;
}
function createTodo(text, id) {
const todo = document.createElement('div');
todo.className = 'todo';
todo.innerText = text;
todo.addEventListener('click', () => {
todos.splice(todos.findIndex(x => x.id === id), 1);
render();
});
return todo;
}