JSFiddle - React, Tailwind, and code Playground

by Boba Poshtar

HTML

<p><button class="add-todo">Add todo</button></p>

<div class="todo-list"></div>

CSS

.todo {
  width: 180px;
  margin: 0 0 8px 0;
  padding: 8px 16px;
  border: 1px solid #000;
}
.todo.done {
  color: #090;
  border-color: #090;
}
.todo-check {
  float: right;
  position: relative;
  margin-left: 8px;
  width: 12px;
  height: 12px;
  border: 1px solid #000;
  cursor: pointer;
}
.done .todo-check {
  border-color: #090;
}
.done .todo-check::before {
  content: "";
  position: absolute;
  left: 2px;
  top: 0;
  width: 6px;
  height: 6px;
  border-right: 2px solid #090;
  border-bottom: 2px solid #090;
  transform: rotate(45deg);
}
.todo-remove {
  float: right;
  padding: 0 4px 2px;
  line-height: 0.8em;
  cursor: pointer;
}

JavaScript

const todos = [
  { text: "Todo 1", id: "1" },
  { text: "Todo 2", id: "2" },
  { text: "Todo 3", id: "3" }
];
const btnAdd = document.querySelector('.add-todo');
const todoList = document.querySelector('.todo-list');

addStartTodos(todos);
window.addEventListener('click', globalClick);
btnAdd.addEventListener('click', () => addTodo());

function addStartTodos(todos){
	todos.forEach(todo => addTodo(todo));
}

function globalClick(e){
	if (e.target.classList.contains('todo-check')) {
  	// клікнули на спан-чекбокс
    e.target.parentElement.classList.toggle('done');
    return;
  }
  if (e.target.classList.contains('todo-remove')) {
  	// клікнули на кнопку видалення
  	e.target.parentElement.remove();
    return;
  }
}

function addTodo(todo){
	const div = document.createElement('div');
  div.classList.add('todo');
  const id = todo ? todo.id : random();
  const text = todo ? todo.text : 'Todo ' + id;
	let html = text + '<span class="todo-check"></span>';
  html += '<button class="todo-remove">remove</button>';
  div.innerHTML = html;
  todoList.appendChild(div);
}

function random() {
	return Math.floor(Math.random() * 1000000);
}