I have created a basic and unstyled to-do list using Javascript. I want the browser to remember the list items when I refresh the page or when I exit the page and revisit it.
I also want the user to be able to click an “X” or something to delete the list item from the browser’s memory and to forget it.
Here’s my code:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>My TO-DOs</title>
</head>
<body>
<div id="header">
<h1>My Todos</h1>
<form>
<label>Add an item:</label>
<input type="text">
<button type="submit">ADD</button>
</form>
</div>
<ul id="itemList"></ul>
<script src="main.js"></script>
</body>
</html>
JavaScript:
const form = document.querySelector('form');
const input = document.querySelector('input');
form.addEventListener('submit', function(e){
e.preventDefault();
if (input.value === '' || input.value === null) {
alert('You cannot add a blank item.');
} else{
const listItem = document.createElement('li');
const listItemText = document.createTextNode(input.value);
listItem.appendChild(listItemText);
const listElement = document.getElementById('itemList');
listElement.appendChild(listItem)
// Clear the input after adding an item
input.value = '';
input.focus();
}});
Here is a code snippet:
const form = document.querySelector('form');
const input = document.querySelector('input');
form.addEventListener('submit', function(e){
e.preventDefault();
if (input.value === '' || input.value === null) {
alert('You cannot add a blank item.');
} else{
const listItem = document.createElement('li');
const listItemText = document.createTextNode(input.value);
listItem.appendChild(listItemText);
const listElement = document.getElementById('itemList');
listElement.appendChild(listItem)
// Clear the input after adding an item
input.value = '';
input.focus();
}});
<!DOCTYPE html>
<html lang="en">
<head>
<title>My TO-DOs</title>
</head>
<body>
<div id="header">
<h1>My Todos</h1>
<form>
<label>Add an item:</label>
<input type="text">
<button type="submit">ADD</button>
</form>
</div>
<ul id="itemList"></ul>
<script src="main.js"></script>
</body>
</html>