Creating Todo List Code
The user wants code likely in vanilla JavaScript to create an event listener that adds items to an unordered list (UL) while also persisting data through localStorage. They didn't specify any framework, so I’ll provide example HTML and JavaScript with a concise explanation. I’ll handle loading from storage and persisting updates on adding items, and while the user didn't explicitly ask for a delete function, I'll include it for simplicity.
The proposed structure will include a form for input and a visible list for todos.Providing Todo List Code
I need to create a simple script for the user, implementing a todo list that saves data to localStorage. First, I’ll define a constant for the storage key and functions to get and save todos. However, I want to keep it simple.
On page load, I'll add an event listener to grab the form and the input field. I'll also preload existing todos from localStorage into the list. The submit event handler helps ensure new todos are pushed to the array and stored properly.
This should give the user a clear, plain JavaScript example without any frameworks. Here’s a minimal, complete example in plain JavaScript that:
- Adds items to a
<ul> when the user submits a form
- Persists the list in
localStorage
- Restores the list on page load
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>To-Do List</title>
</head>
<body>
<form id="todo-form">
<input id="todo-input" type="text" placeholder="Add a to-do..." />
<button type="submit">Add</button>
</form>
<ul id="todo-list"></ul>
<script>
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('todo-form');
const input = document.getElementById('todo-input');
const list = document.getElementById('todo-list');
const STORAGE_KEY = 'todos';
// Load existing todos from localStorage
let todos = JSON.parse(localStorage.getItem(STORAGE_KEY)) || [];
// Helper to add a single item to the DOM
function addTodoToDOM(text) {
const li = document.createElement('li');
li.textContent = text;
list.appendChild(li);
}
// Initial render
todos.forEach(addTodoToDOM);
// Event listener to handle new to-do submissions
form.addEventListener('submit', (e) => {
e.preventDefault();
const text = input.value.trim();
if (!text) return;
// Update in-memory array
todos.push(text);
// Persist to localStorage
localStorage.setItem(STORAGE_KEY, JSON.stringify(todos));
// Update DOM
addTodoToDOM(text);
input.value = '';
input.focus();
});
});
</script>
</body>
</html>