I have an array that contains objects and then the array is stored in localStorage. I want to be able to modify variable inside an the object after it's been stored in localStorage. The item I want to modify is when detecting the corresponding checkbox being checked, I want to change the status of that checkbox from false to true. What's the best way to do that. here's the code
<!DOCTYPE html>
<html>
<head>
<title>TodoList App</title>
<!-- bootstrap cdn -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!-- google fonts -->
<link href="https://fonts.googleapis.com/css?family=Righteous" rel="stylesheet">
<style type="text/css">
/*variables*/
:root {
--righteous-font: 'Righteous', cursive;
}
body {
/*background-color: #536691;*/
background-image: url("http://pctechtips.org/apps/todo/img/Chicago-Wallpaper-3.jpg");
min-height: 100vh;
z-index: -10;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
color: white;
font-size: 1.3rem;
}
.hero {
position: absolute;
min-height: 100vh;
min-width: 100vw;
top: 0;
bottom: 0;
background-color: rgba(31, 34, 118, 0.5);
}
h1 {
margin-top: 12rem;
margin-bottom: 0px;
padding-bottom: 0px;
font-family: var(--righteous-font);
}
.lead {
font-size: 1.5rem;
font-family: var(--righteous-font);
}
/*hr {
margin-top: 2rem;
border: 1px solid white
}*/
ul {
/*border-top: 2px solid white;*/
margin-top: 2rem;
list-style: none;
/*display: none;*/
}
li {
border-bottom: 1px solid white;
padding: 0.5rem 0 0.5rem 0;
margin: 0 1rem 0 1rem;
}
.checkboxes {
float: right;
line-height: 15px;
width: 17px;
height: 17px;
background-color: #e9ecef;
border: 1px solid #e9ecef;
border-radius: 3px;
}
</style>
</head>
<body>
<div class="hero">
<div class="container">
<h1 class="display-2 text-center">TodoList</h1>
<p class="lead text-center">Welcome to my todoList applications</p>
<div class="row">
<form id="form" class="col-8 mx-auto">
<div class="input-group">
<input id="input" class="form-control" placeholder="Enter todo list item" value="this is a todo item list">
<span>
<button id="btn" type="button" class="btn btn-primary">Submit</button>
</span>
</div>
</form>
</div>
<div class="row">
<ul id="list" class="list col-8 mx-auto">
<!-- <li>this is a todo item <input type="checkbox" class="checkbox"></li>
<li>this is a todo item <input type="checkbox" class="checkbox"></li> -->
</ul>
</div>
</div>
</div>
<script type="text/javascript">
window.onload = function() {
//variables
var list = document.getElementById("list");
var input = document.getElementById("input");
var btn = document.getElementById('btn');
var id = 1;
var todoList = [];
//{item: "item", isChecked: "false"};
var todoItem = "";
//button event listener
btn.addEventListener("click", addTodoItem);
//list event listener for checkbox
list.addEventListener("click", boxChecked);
if(localStorage.length > 0) {
displayList();
}
//add todo list item
function addTodoItem() {
if(input.value === "") {
alert("Input field can't be empty!");
}
else {
if(list.style.borderTop === "") {
list.style.borderTop = "2px solid white";
}
var li = document.createElement("li");
var text = document.createTextNode(input.value);
li.id = "li-"+id;
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.className = "checkboxes"
checkbox.id = "box-"+id;
li.appendChild(text);
li.appendChild(checkbox);
list.appendChild(li);
id++;
addToLocalStorage();
}
}
//adding strike through style when checkbox clicked
function boxChecked(event) {
const element = event.target;
//ignore clicks on anything else other than checkbox
if(element.type !== "checkbox") return;
console.log(element.id);
//apply css style
element.parentNode.style.textDecoration = "line-through";
}
//adding items to localstorage
function addToLocalStorage() {
console.log(localStorage.toString());
todoItem = {item: input.value, isChecked: "false"};
todoList.push(todoItem);
//checking localsotorage exists
if(typeof(Storage) !== "undefined") {
localStorage.setItem("todoList", JSON.stringify(todoList));
}
else {
alert("localstorage not available in browser!");
}
}
/* display all todo list items */
function displayList() {
todoList = JSON.parse(localStorage.getItem("todoList"));
list.style.borderTop = "2px solid white";
for(var i = 0; i < todoList.length; i++) {
var li = document.createElement("li");
var text = document.createTextNode(todoList[i].item);
li.id = "li-"+id;
var checkbox = document.createElement("input");
/*if(Boolean(todoList[i].isChecked)) {
checkBox.checked = true;
checkBox.style.textDecoration = "line-through";
}*/
checkbox.type = "checkbox";
checkbox.className = "checkboxes"
checkbox.id = "box-"+id;
li.appendChild(text);
li.appendChild(checkbox);
list.appendChild(li);
id++;
}
}
}
</script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
</body>
</html>
I would make that inside the boxChecked function:
function boxChecked(event) {
const element = event.target;
//ignore clicks on anything else other than checkbox
if(element.type !== "checkbox") return;
var newTodo = JSON.parse(localStorage.getItem("todoList"))[element.id.slice(element.id.length-1)-1];
newTodo.isChecked = element.checked.toString();
var todoList = JSON.parse(localStorage.getItem("todoList"));
todoList[element.id.slice(element.id.length-1)-1] = newTodo;
localStorage.setItem("todoList", JSON.stringify(todoList));
//apply css style
element.parentNode.style.textDecoration = "line-through";
}
Related
Still learning so bear with me.
I am building a test project where I have a simple input that I show it on the same page as a list. (grocery or to do list project)
So when a user hits the ok button I create a new li inside a ul element. That goes ok.
I want to implement the following though: When the user clicks on the new element (li) I want to change the text decoration to line-though and show a trash icon where it will remove this li element by clicking on it.
I have managed to do that. The problem is that when the user clicks again on the new element (li) I get a second trash image.
I want help to succeed in this: when a user clicks on the element while it has text-decoration = line-through to hide or remove the trash icon and make text-decoration none again.
Here is a code pen for this project to check out. Just insert a new item on the list and then click twice on it: https://codepen.io/dourvas-ioannis/pen/MWVBjNZ
This is the function I am using when the user hits the add button to add a list item:
function addToList(){
let newListItem = document.createElement('li');
newListItem.textContent = userInput.value;
list.appendChild(newListItem);
userInput.value = "";
newListItem.addEventListener('click', function(){
this.style.textDecoration = 'line-through';
let itemButton = document.createElement('a');
itemButton.setAttribute('href', '#');
itemButton.classList.add('trash-image');
itemButton.innerHTML = '<i class="material-icons">delete</i><a/>';
itemButton.addEventListener("click", deleteOneItem);
this.appendChild(itemButton);
});
}
function deleteOneItem(){
this.parentNode.remove();
}
//select from DOM
let allItems = document.querySelector('#allItems');
let button = document.querySelector('#add-button');
let userInput = document.querySelector('#item');
let list = document.querySelector('#list');
let clear = document.querySelector('#clear-button');
//add event listener
button.addEventListener('click', addToList);
clear.addEventListener('click', clearAll);
//functions
function addToList() {
let newListItem = document.createElement('li');
newListItem.textContent = userInput.value;
list.appendChild(newListItem);
userInput.value = "";
newListItem.addEventListener('click', function() {
this.style.textDecoration = 'line-through';
let itemButton = document.createElement('a');
itemButton.setAttribute('href', '#');
itemButton.classList.add('trash-image');
itemButton.innerHTML = '<i class="material-icons">delete</i><a/>';
itemButton.addEventListener("click", deleteOneItem);
this.appendChild(itemButton);
});
}
function deleteOneItem() {
this.parentNode.remove();
}
function clearAll() {
list.innerHTML = "";
}
body {
font-size: 10px;
font-family: Arial, Helvetica, sans-serif;
margin: 0;
background-color: antiquewhite;
}
#container {
width: 80%;
margin: auto;
padding-top: 10px;
background-color: rgb(200, 225, 225);
color: rgb(52, 48, 48);
border-radius: 10px;
}
p {
font-size: 20px;
text-align: center;
padding: 30px, 0px, 5px, 0px;
}
#formdiv {
text-align: center;
}
#item {
size: 100px;
}
#clear {
margin-top: 60px;
text-align: center;
}
li {
list-style-type: none;
font-size: 3.2em;
padding: 0.5em;
margin: 1em;
background-color: lightyellow;
border-radius: 5px;
border: 1px solid grey;
}
.trash-image {
float: right;
margin: -2px 3px 3px 3px;
vertical-align: middle;
height: 4px;
}
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<body>
<br> <br> <br>
<div id='container'>
<p>My list</p>
<br>
<div id="formdiv">
<label for="item">add this.. </label><br>
<input type="text" name="item" id="item">
<button id="add-button"> add </button>
</div>
<div id="allItems">
<ul id="list">
</ul>
</div>
<div id="clear">
<button id="clear-button"> Clear List </button><br> <br> <br>
</div>
</div>
Here's a quick example implementation of the approach I mentioned in the comments. I've just hacked it together quickly, so there's a small difference for the bin.
I've used an img (without a src) instead of a 'character' from the
font. I've styled the img to be 16x16 for the same reason. It also
makes it visible instead of being 0x0 pixels. I also set the cursor.
"use strict";
window.addEventListener('load', onLoad, false);
function onLoad(evt) {
document.querySelector('button').addEventListener('click', onAddBtnClicked, false);
}
function onAddBtnClicked(evt) {
let userText = document.querySelector('input').value;
let newLi = document.createElement('li');
newLi.textContent = userText;
newLi.addEventListener('click', onIncompleteItemClicked, false);
document.querySelector('ul').appendChild(newLi);
}
function onIncompleteItemClicked(evt) {
let clickedLi = this;
clickedLi.classList.toggle('itemComplete');
let binImg = document.createElement('img');
binImg.addEventListener('click', onBinIconClicked, false);
clickedLi.appendChild(binImg);
clickedLi.removeEventListener('click', onIncompleteItemClicked, false);
clickedLi.addEventListener('click', onCompletedItemClicked, false);
}
function onCompletedItemClicked(evt) {
let clickedLi = this;
clickedLi.classList.toggle('itemComplete');
let binImg = clickedLi.querySelector('img');
clickedLi.removeChild(binImg);
clickedLi.removeEventListener('click', onCompletedItemClicked, false);
clickedLi.addEventListener('click', onIncompleteItemClicked, false);
}
function onBinIconClicked(evt) {
let clickedBin = this;
let containingLi = clickedBin.parentNode;
containingLi.remove();
}
.itemComplete {
text-decoration: line-through;
}
li>img {
cursor: pointer;
width: 16px;
height: 16px;
}
<input value='blah-blah'></input><button>Add</button>
<ul></ul>
Add a variable indicating that the icon has been already added.
Check if icon is added on click
If yes - skip
If not - set icon
//select from DOM
let allItems = document.querySelector('#allItems');
let button = document.querySelector('#add-button');
let userInput = document.querySelector('#item');
let list = document.querySelector('#list');
let clear = document.querySelector('#clear-button');
//add event listener
button.addEventListener('click', addToList);
clear.addEventListener('click', clearAll);
//functions
function addToList() {
let newListItem = document.createElement('li');
newListItem.textContent = userInput.value;
list.appendChild(newListItem);
userInput.value = "";
// declare boolean variable
let hasTrashIcon = false
newListItem.addEventListener('click', function() {
// if has thrash icon skip
if (hasTrashIcon) return
// set has trash icon
hasTrashIcon = true
this.style.textDecoration = 'line-through';
let itemButton = document.createElement('a');
itemButton.setAttribute('href', '#');
itemButton.classList.add('trash-image');
itemButton.innerHTML = '<i class="material-icons">delete</i><a/>';
itemButton.addEventListener("click", deleteOneItem);
this.appendChild(itemButton);
});
}
function deleteOneItem() {
this.parentNode.remove();
}
function clearAll() {
list.innerHTML = "";
}
body {
font-size: 10px;
font-family: Arial, Helvetica, sans-serif;
margin: 0;
background-color: antiquewhite;
}
#container {
width: 80%;
margin: auto;
padding-top: 10px;
background-color: rgb(200, 225, 225);
color: rgb(52, 48, 48);
border-radius: 10px;
}
p {
font-size: 20px;
text-align: center;
padding: 30px, 0px, 5px, 0px;
}
#formdiv {
text-align: center;
}
#item {
size: 100px;
}
#clear {
margin-top: 60px;
text-align: center;
}
li {
list-style-type: none;
font-size: 3.2em;
padding: 0.5em;
margin: 1em;
background-color: lightyellow;
border-radius: 5px;
border: 1px solid grey;
}
.trash-image {
float: right;
margin: -2px 3px 3px 3px;
vertical-align: middle;
height: 4px;
}
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<body>
<br> <br> <br>
<div id='container'>
<p>My list</p>
<br>
<div id="formdiv">
<label for="item">add this.. </label><br>
<input type="text" name="item" id="item">
<button id="add-button"> add </button>
</div>
<div id="allItems">
<ul id="list">
</ul>
</div>
<div id="clear">
<button id="clear-button"> Clear List </button><br> <br> <br>
</div>
</div>
I have tried to insert the data into the ToDo List and it is working but i am unable to edit the name and number field in the edit box of ToDo list.
And also the list is showing is not properly having padding and i tried to put padding in the list but whole list is shifting towards the left.
Also I tried with table concept in JavaScript but for that i need the loop and the database but i dont want to use the database or any other storage
var taskInput = document.getElementById("new-task");
var nameInput = document.getElementById("new-name");
var numberInput = document.getElementById("new-number");
var addButton = document.getElementsByTagName("button")[0];
var incompleteTask = document.getElementById("incomplete-tasks");
var completedTask = document.getElementById("completed-tasks");
var createNewTaskElement = function (taskString, nameString, numberString) {
var listItem = document.createElement("li");
var checkBox = document.createElement("input");
var label = document.createElement("label");
var label1 = document.createElement("label1");
var label2 = document.createElement("label2");
var editInput = document.createElement("input");
var editInput1 = document.createElement("input");
var editInput2 = document.createElement("input");
var editButton = document.createElement("button");
var deleteButton = document.createElement("button");
label.innerText = taskString;
label1.innerText = nameString;
label2.innerText = numberString;
checkBox.type = "checkbox";
editInput.type = "text";
editInput1.type = "text";
editInput2.type = "text";
editButton.innerText = "Edit";
editButton.className = "edit";
deleteButton.innerText = "Delete";
deleteButton.className = "delete";
listItem.appendChild(checkBox);
listItem.appendChild(label);
listItem.appendChild(editInput);
listItem.appendChild(label1);
listItem.appendChild(editInput1);
listItem.appendChild(label2);
listItem.appendChild(editInput2);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
alert("You added '" + label.innerText + "' to the ToDO list");
return listItem;
}
var addTask = function () {
var listItem = createNewTaskElement(taskInput.value,nameInput.value,numberInput.value);
if (taskInput.value == "") {
alert("You must enter a task");
}
else if (nameInput.value == "") {
alert("You must enter a Name");
}
else if (numberInput.value == "") {
alert("You must enter a Phone Number");
} else {
incompleteTask.appendChild(listItem);
}
bindTaskEvents(listItem, taskCompleted);
taskInput.value = "";
nameInput.value = "";
numberInput.value = "";
}
var editTask = function () {
var listItem = this.parentNode;
var editInput = listItem.querySelector('input[type=text]');
var label = listItem.querySelector("label");
var containsClass = listItem.classList.contains("editMode");
if (containsClass) {
label.innerText = editInput.value;
alert("You edited " + label.innerText);
} else {
editInput.value = label.innerText;
}
listItem.classList.toggle("editMode");
}
var deleteTask = function () {
var listItem = this.parentNode;
var ul = listItem.parentNode;
alert("You deleted " + listItem.querySelector("label").innerText);
ul.removeChild(listItem);
}
var taskCompleted = function () {
var listItem = this.parentNode;
completedTask.appendChild(listItem);
bindTaskEvents(listItem, taskIncomplete);
alert("You completed " + listItem.querySelector("label").innerText);
}
var taskIncomplete = function () {
var listItem = this.parentNode;
incompleteTask.appendChild(listItem);
bindTaskEvents(listItem, taskCompleted);
}
var bindTaskEvents = function (taskListItem, checkBoxEventHandler) {
var checkBox = taskListItem.querySelector("input[type=checkbox]");
var editButton = taskListItem.querySelector("button.edit");
var deleteButton = taskListItem.querySelector("button.delete");
editButton.onclick = editTask;
deleteButton.onclick = deleteTask;
checkBox.onchange = checkBoxEventHandler;
}
for (var i = 0; i < incompleteTask.children.length; i++) {
bindTaskEvents(incompleteTask.children[i], taskCompleted);
}
for (var i = 0; i < completedTask.children.length; i++) {
bindTaskEvents(completedTask.children[i], taskIncomplete);
}
var input = document.getElementById("new-number");
input.addEventListener("keypress", function (event) {
if (event.key === "Enter") {
addTask();
}
});
.container {
height: 525px;
width: 450px;
margin: 100px auto;
}
ul {
margin: 0;
padding: 0;
}
li * {
float: left;
}
li,
h3 {
clear: both;
list-style: none;
font-family: Arial, Helvetica, sans-serif;
}
input,button {
outline: none;
}
button {
background: none;
border: 0px;
color: #888;
font-size: 15px;
width: 60px;
margin: 10px 0 0;
font-family: Lato, sans-serif;
cursor: pointer;
}
button:hover {
color: #333;
}
h3, label[for='new-task'] {
color: #333;
font-weight: 700;
font-size: 15px;
border-bottom: 2px solid #333;
padding: 30px 0 10px;
margin: 0;
text-transform: uppercase;
}
input[type="text"] {
margin: 0;
font-size: 18px;
line-height: 18px;
height: 18px;
padding: 10px;
border: 1px solid #ddd;
background: #fff;
border-radius: 8px;
font-family: Lato, sans-serif;
color: #888;
margin-left: 50px;
}
input[type="text"]:focus {
color: #333;
}
label[for='new-task'] {
display: block;
margin: 0 0 20px;
}
input#new-task,#new-name,#new-number {
width: 260px;
margin-bottom: 10px;
}
input:focus{
outline: none;
box-shadow: 0px 0px 5px #61C5FA;
border-color: #5AB0DB;
}
input:hover {
border: 1px solid #999;
border-radius: 5px;
}
p>button:hover {
color: #0FC57C;
}
li {
overflow: hidden;
padding: 20px 0;
border-bottom: 1px solid #eee;
}
li>input[type="checkbox"] {
margin: 0 10px;
position: relative;
top: 15px;
}
li>label {
font-size: 18px;
line-height: 40px;
width: 190px;
padding: 0 0 0 11px;
}
li>input[type="text"] {
width: 180px;
}
#completed-tasks label {
text-decoration: line-through;
color: #888;
}
ul li input[type=text] {
display: none;
}
ul li.editMode input[type=text] {
display: block;
}
ul li.editMode label {
display: none;
}
th{
padding-right: 70px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css" type="text/css">
<title>To DO List</title>
</head>
<body style="background-color: #ebeff0">
<div class="container">
<h3 style="text-align: center;">Add Task</h3>
<br>
<label>Add Task</label>
<input id="new-task" type="text" required><br>
<label>Name</label>
<input id="new-name" type="text" required><br>
<label>Phone Number</label>
<input id="new-number" type="text" required><br>
<h3 style="text-align: center;">Todo</h3>
<ul id="incomplete-tasks">
</ul>
<h3 style="text-align: center;">Completed Tasks</h3>
<ul id="completed-tasks">
</ul>
</div>
</body>
<script type="text/javascript" src="main.js"></script>
</html>
I have created the class and then edited the inputs
var taskInput = document.getElementById("new-task");
var nameInput = document.getElementById("new-name");
var numberInput = document.getElementById("new-number");
var addButton = document.getElementsByTagName("button")[0];
var incompleteTask = document.getElementById("incomplete-tasks");
var completedTask = document.getElementById("completed-tasks");
var createNewTaskElement = function (taskString, nameString, numberString) {
var listItem = document.createElement("li");
var checkBox = document.createElement("input");
var label = document.createElement("label");
var label1 = document.createElement("label");
var label2 = document.createElement("label");
var editInput = document.createElement("input");
var editInput1 = document.createElement("input");
var editInput2 = document.createElement("input");
var editButton = document.createElement("button");
var deleteButton = document.createElement("button");
label.innerText = taskString;
label1.innerText = nameString;
label2.innerText = numberString;
label.className = "task";
label1.className = "name";
label2.className = "number";
checkBox.type = "checkbox";
editInput.type = "text";
editInput1.type = "text";
editInput2.type = "text";
editInput.className = "edit";
editInput1.className = "edit1";
editInput2.className = "edit2";
editButton.innerText = "Edit";
editButton.className = "edit";
deleteButton.innerText = "Delete";
deleteButton.className = "delete";
listItem.appendChild(checkBox);
listItem.appendChild(label);
listItem.appendChild(editInput);
listItem.appendChild(label1);
listItem.appendChild(editInput1);
listItem.appendChild(label2);
listItem.appendChild(editInput2);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
alert("You added '" + label.innerText + "' to the ToDO list");
return listItem;
}
var addTask = function () {
var listItem = createNewTaskElement(taskInput.value, nameInput.value, numberInput.value);
if (taskInput.value == "") {
alert("You must enter a task");
} else if (nameInput.value == "") {
alert("You must enter a Name");
} else if (numberInput.value == "") {
alert("You must enter a Phone Number");
} else {
incompleteTask.appendChild(listItem);
}
bindTaskEvents(listItem, taskCompleted);
taskInput.value = "";
nameInput.value = "";
numberInput.value = "";
}
var editTask = function () {
var listItem = this.parentNode;
var editInput = listItem.querySelector('.edit');
var editInput1 = listItem.querySelector('.edit1');
var editInput2 = listItem.querySelector('.edit2');
var label = listItem.querySelector(".task");
var label1 = listItem.querySelector(".name");
var label2 = listItem.querySelector(".number");
var containsClass = listItem.classList.contains("editMode");
if (containsClass) {
label.innerText = editInput.value;
label1.innerText = editInput1.value;
label2.innerText = editInput2.value;
alert("You edited " + label.innerText);
} else {
editInput.value = label.innerText;
editInput1.value = label1.innerText;
editInput2.value = label2.innerText;
}
listItem.classList.toggle("editMode");
}
var deleteTask = function () {
if (confirm("Are you sure you want to delete this task?") == true) {
var listItem = this.parentNode;
var ul = listItem.parentNode;
alert("You deleted " + listItem.querySelector("label").innerText);
} else {
alert("You cancelled the task");
}
ul.removeChild(listItem);
}
var taskCompleted = function () {
var listItem = this.parentNode;
if (confirm("Are you sure you want to mark this task as complete?") == true) {
completedTask.appendChild(listItem);
bindTaskEvents(listItem, taskIncomplete);
alert("You completed " + listItem.querySelector("label").innerText);
} else {
alert("You cancelled the task");
}
}
var taskIncomplete = function () {
var listItem = this.parentNode;
incompleteTask.appendChild(listItem);
bindTaskEvents(listItem, taskCompleted);
}
var bindTaskEvents = function (taskListItem, checkBoxEventHandler) {
var checkBox = taskListItem.querySelector("input[type=checkbox]");
var editButton = taskListItem.querySelector("button.edit");
var deleteButton = taskListItem.querySelector("button.delete");
editButton.onclick = editTask;
deleteButton.onclick = deleteTask;
checkBox.onchange = checkBoxEventHandler;
}
for (var i = 0; i < incompleteTask.children.length; i++) {
bindTaskEvents(incompleteTask.children[i], taskCompleted);
}
for (var i = 0; i < completedTask.children.length; i++) {
bindTaskEvents(completedTask.children[i], taskIncomplete);
}
var input = document.getElementById("new-number");
.container {
height: 525px;
width: 700px;
margin: 100px auto;
}
ul {
margin: 0;
padding: 0;
}
li * {
float: left;
}
li,
h3 {
clear: both;
list-style: none;
font-family: Arial, Helvetica, sans-serif;
}
input,button {
outline: none;
}
button {
background: none;
border: 0px;
color: #888;
font-size: 15px;
width: 60px;
margin: 10px 0 0;
font-family: Lato, sans-serif;
cursor: pointer;
}
button:hover {
color: #333;
}
h3, label[for='new-task'] {
color: #333;
font-weight: 700;
font-size: 15px;
border-bottom: 2px solid #333;
padding: 30px 0 10px;
margin: 0;
text-transform: uppercase;
}
input[type="text"] {
margin: 0;
font-size: 18px;
line-height: 18px;
height: 18px;
padding: 10px;
border: 1px solid #ddd;
background: #fff;
border-radius: 8px;
font-family: Lato, sans-serif;
color: #888;
margin-left: 50px;
}
input[type="text"]:focus {
color: #333;
}
label[for='new-task'] {
display: block;
margin: 0 0 20px;
}
input#new-task,#new-name,#new-number {
width: 260px;
margin-bottom: 10px;
}
input:focus{
outline: none;
box-shadow: 0px 0px 5px #61C5FA;
border-color: #5AB0DB;
}
input:hover {
border: 1px solid #999;
border-radius: 5px;
}
p>button:hover {
color: #0FC57C;
}
li {
overflow: hidden;
padding: 20px 0;
border-bottom: 1px solid #eee;
}
li>input[type="checkbox"] {
margin: 0 10px;
position: relative;
top: 15px;
}
li>label {
font-size: 18px;
line-height: 40px;
width: 100px;
padding: 0 0 0 11px;
}
li>input[type="text"] {
width: 100px;
}
li>button{
padding-left: 3px;
}
li>button:hover{
border: 1px solid black;
color: #c54f0f;
}
#completed-tasks label {
text-decoration: line-through;
color: #888;
}
ul li input[type=text] {
display: none;
}
ul li.editMode input[type=text] {
display: block;
}
ul li.editMode label {
display: none;
}
#AddBtn{
align-items: center;
border: 1px solid black !important;
background-color: white;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css" type="text/css">
<title>To DO List</title>
</head>
<body style="background-color: #ebeff0">
<div class="container">
<h3 style="text-align: center;">Add Task</h3>
<br>
<label>Add Task</label>
<input id="new-task" type="text" required><br>
<label style="padding-right: 05px;">Name</label>
<input id="new-name" type="text" required><br>
<label>Phone Number</label>
<input id="new-number" type="text" required><br>
<button id="AddBtn" onclick="addTask()">Add</button>
<h3 style="text-align: center;">Todo</h3>
<ul id="incomplete-tasks">
</ul>
<h3 style="text-align: center;">Completed Tasks</h3>
<ul id="completed-tasks">
</ul>
</div>
</body>
<script type="text/javascript" src="main.js"></script>
</html>
I created a to-do list so when you add something into the textbox and click the add button it adds it into the list which is shown below it. However, I want to quickly add a bunch of things and not tediously use my mouse to click the add button every time, that's why I have been trying to add in the function for when I press enter it will be added. But everything I've tried hasn't been working and yes I've read through and attempted to use code from other questions on stackoverflow which is why I've finally decided to ask this question.
Please help! [the end of the JavaScript part of the snippet is my most recent attempt]
// Create a "close" button and append it to each list item
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
}
}, false);
// Create a new list item when clicking on the "Add" button
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '') {
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
window.addEventListener('keyup', function (e) {
if (e.keyCode === 13) {
var button = document.getElementById("myInput");
button.click();
}
}, false);
}
body {
background-color: #81B9E3;
font-family: 'Handlee', cursive;
}
h1 {
color: #2F90DA;
font-size: xxx-large;
font-family: 'Concert One', cursive;
}
a {
text-decoration: none;
color: #2F90DA;
}
p{
color: black;
}
body {
margin: 0;
min-width: 250px;
}
/* Include the padding and border in an element's total width and height */
* {
box-sizing: border-box;
}
/* Remove margins and padding from the list */
ul {
margin: 0;
padding: 0;
}
/* Style the list items */
ul li {
cursor: pointer;
position: relative;
padding: 12px 8px 12px 40px;
list-style-type: none;
background: #7DB9FF;
font-size: 18px;
transition: 0.2s;
/* make the list items unselectable */
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Set all odd list items to a different color (zebra-stripes) */
ul li:nth-child(odd) {
background: #93C5FF;
}
/* Darker background-color on hover */
ul li:hover {
background: #51CA4C;
}
/* When clicked on, add a background color and strike out text */
ul li.checked {
background: #9DF599;
color: #51CA4C;
text-decoration: line-through;
}
/* Add a "checked" mark when clicked on */
ul li.checked::before {
content: '';
position: absolute;
border-color: #51CA4C;
border-style: solid;
border-width: 0 2px 2px 0;
top: 10px;
left: 16px;
transform: rotate(45deg);
height: 15px;
width: 7px;
}
/* Style the close button */
.close {
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.close:hover {
background-color: #F44336;
color: white;
}
/* Style the header */
.header {
background-color: #2F90DA;
padding: 30px 40px;
color: white;
text-align: center;
}
/* Clear floats after the header */
.header:after {
content: "";
display: table;
clear: both;
}
/* Style the input */
input {
margin: 0;
border: none;
border-radius: 0;
width: 75%;
padding: 10px;
float: left;
font-size: 16px;
}
/* Style the "Add" button */
.addBtn {
padding: 8.5px;
width: 25%;
background: #81B9E3;
color: #fff;
float: left;
text-align: center;
font-size: 16px;
cursor: pointer;
transition: 0.3s;
border-radius: 0;
}
.addBtn:hover {
background-color: #51CA4C;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>To Do List</title>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Actor&family=Luckiest+Guy&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Concert+One&family=Handlee&family=Actor&display=swap" rel="stylesheet">
<link href="todo.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div style="background-color: #DCEEF5; padding: 20px; text-align: center;">
<h1> 📖 To Do List 📖</h1>
<h2 style="margin-top: 0; margin-left: 20%; margin-right: 20%">Make your own to do list!</h2>
<h3>Type your task and click "Add". Once your task is completed, just click on the task to cross it off. Press the x button on the far right of a task to remove it.</h3>
<h4 style="margin-bottom: 3%;">Go back to Productify Home or Navigation</h4>
</div><br/>
</body>
<style>
</style>
</head>
<body>
<div id="myDIV" class="header">
<h2 style="margin:5px">📖 My To Do List 📖</h2>
<input type="text" id="myInput" placeholder="New Task...">
<span onclick="newElement()" class="addBtn">Add</span>
</div>
<ul id="myUL"></ul>
<script src="todo.js"></script>
</body>
</html>
You can probably get away with using the same handler for both the button and the input using a closure.
// Cache your elements
const input = document.querySelector('input');
const list = document.querySelector('div');
const button = document.querySelector('button');
// Pass in the input and list elements to the handler
// The handler returns a new function that will be used
// for both the button and input listeners
const handler = handleInput(input, list);
button.addEventListener('click', handler, false);
input.addEventListener('keyup', handler, false);
function handleInput(input, list) {
// Initialise the text in the input
let text = '';
// Add the text to the page, reset `text`,
// and reset the input value
function printLine(text) {
list.innerHTML += `<div>${text}</div>`;
text = '';
input.value = '';
}
// This is the listener
return function(e) {
const { code, target: { value, type } } = e;
// If the button is clicked call `printLine`
if (type === 'submit') printLine(text);
// If the input has changed
// If return has been pressed call printLine
// otherwise update the text value
if (type === 'text') {
if (code === 'Enter') {
printLine(text);
} else {
text = value;
}
}
}
}
<input />
<button>Add to list</button>
<div></div>
I am beginning to learn JavaScript and wanted to start a project to test myself. The classic to do list project.
I have created a function that basically pulls whatever text is in the input box and creates a new list item using that text. However, the delete button is only appearing on the most recent item in the list.
I can fix this by nesting the [var deleteButton = document.createElement('button');] (line 4) within the function, but when I do this the delete button no longer functions!
Any help at all would be really appreciated. (also, I know that is is not mobile responsive yet, I am planning to work on all of that after getting the functionality nailed).
Code:
$(document).ready(function() {
var submitButton = $('#taskEntryButton');
var taskEntry = $('#taskEntryField');
var deleteButton = document.createElement('button');
function submitFunction() {
// get the input value and put it into a variable
var newTaskContent = $('#taskEntryField').val();
// create a new list item
var newListItem = document.createElement('li');
// create a new checkbox for the new list item
var newCheckbox = document.createElement('INPUT');
newCheckbox.setAttribute('type', 'checkbox');
newListItem.appendChild(newCheckbox);
newCheckbox.setAttribute('class', '.activeCheckBox');
// create a new 'label' in the list item
var label = document.createElement('label');
label.innerText = newTaskContent;
newCheckbox.after(label);
// create a new div for the delete button
var buttonHolder = document.createElement('div');
buttonHolder.setAttribute('class', '.newButtonHolder');
label.after(buttonHolder);
// create the delete button
deleteButton.setAttribute('class', '.delete');
deleteButton.innerText = "Delete";
buttonHolder.appendChild(deleteButton);
// insert the new list item into the list (at the top)
$('#activeTaskList').prepend(newListItem);
// reset text box
taskEntry.val("");
};
submitButton.click(submitFunction);
// make function execute on enter
taskEntry.keypress(function(event) {
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
submitFunction();
// reset text box
taskEntry.val("");
}
});
// set up the delete button
deleteButton.addEventListener("click", deleteItem);
//delete function
function deleteItem() {
// grab list item (button -> div -> li)
let item = this.parentNode.parentNode;
// here i select the ul
let parent = item.parentNode;
//remove li from ul
parent.removeChild(item);
};
// here i make the 2 tab buttons show the relevent tab
var activeTabButton = document.getElementById('activeButton');
var completedTabButton = document.getElementById('completedButton');
var activeTab = document.getElementById('activeTasks');
var completedTab = document.getElementById('completedTasks');
activeTabButton.addEventListener("click", function() {
if (activeTab.style.display !== "block") {
activeTab.style.display = "block";
completedTab.style.display = "none";
};
});
completedTabButton.addEventListener("click", function() {
if (completedTab.style.display !== "block") {
completedTab.style.display = "block";
activeTab.style.display = "none";
};
});
});
* {
font-family: 'Karla', sans-serif;
}
body {
background-color: rgb(226, 217, 198);
}
.wrapper {
width: 100%;
height: 100vh;
display: flex;
}
#container {
background-color: #ffe8aa;
width: 30%;
height: 650px;
margin-left: auto;
margin-right: auto;
align-self: center;
border-radius: 20px;
}
#header {
height: 170px;
background-color: rgb(255, 189, 113);
display: flex;
flex-direction: column;
align-items: center;
border-radius: 20px 20px 0px 0px;
}
.tabsButton {
font-size: 1.2em;
width: 150px;
text-align: center;
border-style: none;
margin-left: 10px;
margin-right: 10px;
}
#taskEntryContainer {
margin-top: auto;
margin-bottom: auto;
display: flex;
}
#taskEntryField {
font-size: 1.2em;
}
#taskEntryButton {
margin-left: 50px;
font-size: 1.2em;
}
/* Task Lists */
#mainSection {
width: 100%;
}
#toDoListContainer {
width: 100%;
overflow: hidden;
border-radius: 0px 0px 20px 20px;
}
.taskList {
width: 100%;
list-style: none;
font-size: 1.5em;
}
.taskList li {
width: 86%;
display: flex;
align-items: baseline;
padding: 2%;
box-sizing: border-box;
border-radius: 10px;
margin-bottom: 20px;
background-color: #ffc038;
}
.taskList li label {
margin-left: 30px;
width: 75%;
}
.taskList button {
border-style: none;
background-color: #494949;
font-size: 0.7em;
color: white;
}
/* Active Tasks */
#activeTasks {
display: block;
z-index: 3;
}
/* Completed Tasks */
#completedTasks {
display: none;
z-index: 3;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>To Do List</title>
<link href="styles.css" rel="stylesheet">
<script src="../jquery-3.5.1.js"></script>
<script src="scripts.js"></script>
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Karla&display=swap" rel="stylesheet">
</head>
<body>
<div class="wrapper">
<div id="container">
<div id="header">
<div id="toDoTabs">
<button class="tabsButton" id="activeButton">Active</button>
<button class="tabsButton" id="completedButton">Completed</button>
</div>
<div id="taskEntryContainer">
<input type="text" id="taskEntryField" input="" placeholder="Enter a new task...">
<button id="taskEntryButton">Submit</button>
</div>
</div>
<div id="mainSection">
<div id="toDoListContainer">
<div id="activeTasks">
<ul class="taskList" id="activeTaskList">
</ul>
</div>
<div id="completedTasks">
<ul class="taskList" id="completedTaskList">
</ul>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
You should indeed create the button inside the submit function and then add the click event handler to that button (also inside the submit function). Because you only created the button once, every time when you append that button to some element it will just "move" the element.
$(document).ready(function() {
var submitButton = $('#taskEntryButton');
var taskEntry = $('#taskEntryField');
function submitFunction() {
// get the input value and put it into a variable
var newTaskContent = $('#taskEntryField').val();
// create a new list item
var newListItem = document.createElement('li');
// create a new checkbox for the new list item
var newCheckbox = document.createElement('INPUT');
newCheckbox.setAttribute('type', 'checkbox');
newListItem.appendChild(newCheckbox);
newCheckbox.setAttribute('class', '.activeCheckBox');
// create a new 'label' in the list item
var label = document.createElement('label');
label.innerText = newTaskContent;
newCheckbox.after(label);
// create a new div for the delete button
var buttonHolder = document.createElement('div');
buttonHolder.setAttribute('class', '.newButtonHolder');
/**
* NOTE HERE!!!
**/
var deleteButton = document.createElement("button");
// set up the delete button
deleteButton.addEventListener("click", deleteItem);
//delete function
function deleteItem() {
// grab list item (button -> div -> li)
let item = this.parentNode.parentNode;
// here i select the ul
let parent = item.parentNode;
//remove li from ul
parent.removeChild(item);
};
label.after(buttonHolder);
// create the delete button
deleteButton.setAttribute('class', '.delete');
deleteButton.innerText = "Delete";
buttonHolder.appendChild(deleteButton);
// insert the new list item into the list (at the top)
$('#activeTaskList').prepend(newListItem);
// reset text box
taskEntry.val("");
};
submitButton.click(submitFunction);
// make function execute on enter
taskEntry.keypress(function(event) {
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
submitFunction();
// reset text box
taskEntry.val("");
}
});
// here i make the 2 tab buttons show the relevent tab
var activeTabButton = document.getElementById('activeButton');
var completedTabButton = document.getElementById('completedButton');
var activeTab = document.getElementById('activeTasks');
var completedTab = document.getElementById('completedTasks');
activeTabButton.addEventListener("click", function() {
if (activeTab.style.display !== "block") {
activeTab.style.display = "block";
completedTab.style.display = "none";
};
});
completedTabButton.addEventListener("click", function() {
if (completedTab.style.display !== "block") {
completedTab.style.display = "block";
activeTab.style.display = "none";
};
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="wrapper">
<div id="container">
<div id="header">
<div id="toDoTabs">
<button class="tabsButton" id="activeButton">Active</button>
<button class="tabsButton" id="completedButton">Completed</button>
</div>
<div id="taskEntryContainer">
<input type="text" id="taskEntryField" input="" placeholder="Enter a new task...">
<button id="taskEntryButton">Submit</button>
</div>
</div>
<div id="mainSection">
<div id="toDoListContainer">
<div id="activeTasks">
<ul class="taskList" id="activeTaskList">
</ul>
</div>
<div id="completedTasks">
<ul class="taskList" id="completedTaskList">
</ul>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
You create the button outside the submitFunction function and use it more and more.
Move this line:
var deleteButton = document.createElement('button');
after:
// create the delete button
And, move also the event listener immediately after:
deleteButton.addEventListener("click", deleteItem);
Another solution is to create a clone of your button in your submitFunction using:
Node.cloneNode(): plain javascript
.clone(): using jQuery
The snippet:
$(document).ready(function() {
var submitButton = $('#taskEntryButton');
var taskEntry = $('#taskEntryField');
function submitFunction() {
// get the input value and put it into a variable
var newTaskContent = $('#taskEntryField').val();
// create a new list item
var newListItem = document.createElement('li');
// create a new checkbox for the new list item
var newCheckbox = document.createElement('INPUT');
newCheckbox.setAttribute('type', 'checkbox');
newListItem.appendChild(newCheckbox);
newCheckbox.setAttribute('class', '.activeCheckBox');
// create a new 'label' in the list item
var label = document.createElement('label');
label.innerText = newTaskContent;
newCheckbox.after(label);
// create a new div for the delete button
var buttonHolder = document.createElement('div');
buttonHolder.setAttribute('class', '.newButtonHolder');
label.after(buttonHolder);
// create the delete button
var deleteButton = document.createElement('button'); // MOVE HERE
// set up the delete button
deleteButton.addEventListener("click", deleteItem);
deleteButton.setAttribute('class', '.delete');
deleteButton.innerText = "Delete";
buttonHolder.appendChild(deleteButton);
// insert the new list item into the list (at the top)
$('#activeTaskList').prepend(newListItem);
// reset text box
taskEntry.val("");
};
submitButton.click(submitFunction);
// make function execute on enter
taskEntry.keypress(function(event) {
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
submitFunction();
// reset text box
taskEntry.val("");
}
});
//delete function
function deleteItem() {
// grab list item (button -> div -> li)
let item = this.parentNode.parentNode;
// here i select the ul
let parent = item.parentNode;
//remove li from ul
parent.removeChild(item);
};
// here i make the 2 tab buttons show the relevent tab
var activeTabButton = document.getElementById('activeButton');
var completedTabButton = document.getElementById('completedButton');
var activeTab = document.getElementById('activeTasks');
var completedTab = document.getElementById('completedTasks');
activeTabButton.addEventListener("click", function() {
if (activeTab.style.display !== "block") {
activeTab.style.display = "block";
completedTab.style.display = "none";
};
});
completedTabButton.addEventListener("click", function() {
if (completedTab.style.display !== "block") {
completedTab.style.display = "block";
activeTab.style.display = "none";
};
});
});
* {
font-family: 'Karla', sans-serif;
}
body {
background-color: rgb(226, 217, 198);
}
.wrapper {
width: 100%;
height: 100vh;
display: flex;
}
#container {
background-color: #ffe8aa;
width: 30%;
height: 650px;
margin-left: auto;
margin-right: auto;
align-self: center;
border-radius: 20px;
}
#header {
height: 170px;
background-color: rgb(255, 189, 113);
display: flex;
flex-direction: column;
align-items: center;
border-radius: 20px 20px 0px 0px;
}
.tabsButton {
font-size: 1.2em;
width: 150px;
text-align: center;
border-style: none;
margin-left: 10px;
margin-right: 10px;
}
#taskEntryContainer {
margin-top: auto;
margin-bottom: auto;
display: flex;
}
#taskEntryField {
font-size: 1.2em;
}
#taskEntryButton {
margin-left: 50px;
font-size: 1.2em;
}
/* Task Lists */
#mainSection {
width: 100%;
}
#toDoListContainer {
width: 100%;
overflow: hidden;
border-radius: 0px 0px 20px 20px;
}
.taskList {
width: 100%;
list-style: none;
font-size: 1.5em;
}
.taskList li {
width: 86%;
display: flex;
align-items: baseline;
padding: 2%;
box-sizing: border-box;
border-radius: 10px;
margin-bottom: 20px;
background-color: #ffc038;
}
.taskList li label {
margin-left: 30px;
width: 75%;
}
.taskList button {
border-style: none;
background-color: #494949;
font-size: 0.7em;
color: white;
}
/* Active Tasks */
#activeTasks {
display: block;
z-index: 3;
}
/* Completed Tasks */
#completedTasks {
display: none;
z-index: 3;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Karla&display=swap" rel="stylesheet">
<div class="wrapper">
<div id="container">
<div id="header">
<div id="toDoTabs">
<button class="tabsButton" id="activeButton">Active</button>
<button class="tabsButton" id="completedButton">Completed</button>
</div>
<div id="taskEntryContainer">
<input type="text" id="taskEntryField" input="" placeholder="Enter a new task...">
<button id="taskEntryButton">Submit</button>
</div>
</div>
<div id="mainSection">
<div id="toDoListContainer">
<div id="activeTasks">
<ul class="taskList" id="activeTaskList">
</ul>
</div>
<div id="completedTasks">
<ul class="taskList" id="completedTaskList">
</ul>
</div>
</div>
</div>
</div>
</div>
I made a to do list, all the functions work but I cant figure out how to put spaces in between the input, and delete button, then align the delete button just like the checkboxs. After many inputs are enter the entire list just looks cluttered.
var inputItem = document.getElementById("inputItem");
inputItem.focus();
// adds input Item to list
function addItem(list, input) {
var inputItem = this.inputItem;
var list = document.getElementById(list);
var listItem = document.createElement("li");
// Configure the delete button
var deleteButton = document.createElement("button");
deleteButton.innerText = "X";
deleteButton.addEventListener("click", function() {
this.parentElement.style.display = 'none';
});
// Configure the check box
var checkBox = document.createElement("input");
checkBox.id = "check";
checkBox.type = 'checkbox';
checkBox.addEventListener('change', function() {
labelText.style.textDecoration = checkBox.checked ? 'line-through' : 'none';
});
// Configure the label
var label = document.createElement("label");
var labelText = document.createElement("span");
labelText.innerText = input.value;
// Put the checkbox and label text in to the label element
label.appendChild(checkBox);
label.appendChild(labelText);
// Put the label (with the checkbox inside) and the delete
// button into the list item.
listItem.appendChild(label);
listItem.appendChild(deleteButton);
list.appendChild(listItem);
inputItem.focus();
inputItem.select();
return false;
}
localStorage.setItem("list", list);
localStorage.getItem("list").forEach(function(list) {
elem.textContent = list;
});
body {
text-align: center;
}
form {
display: inline-block;
}
#outerDiv {
padding: 30px;
text-align: center;
}
#innerDiv {
margin: auto;
width: 200px;
height: 100px;
}
ul {
padding: 0;
margin: 0;
}
ul li {
position: relative;
padding: 12px 8px 12px 40px;
background: rgb(148, 160, 181);
list-style-type: none;
font-size: 18px;
}
#submit {
position: absolute;
padding: 10px 16px;
}
/* Style the input */
input {
margin: 0;
border: none;
border-radius: 0;
padding: 10px;
float: left;
font-size: 16px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<h1 align="center"> To-Do List </h1>
<body>
<div id="outerDiv">
<form onsubmit="return addItem('list', this.inputItem)">
<input type="text" id="inputItem" onfocus="this.value=''" onselect="this.value=''" placeholder="Enter a Task">
<input id="submit" type="submit">
</form>
</div>
<div id="innerDiv">
<ul id="list"></ul>
</div>
<script>
var inputItem = document.getElementById("inputItem");
inputItem.focus();
// adds input Item to list
function addItem(list, input) {
var inputItem = this.inputItem;
var list = document.getElementById(list);
var listItem = document.createElement("li");
// Configure the delete button
var deleteButton = document.createElement("button");
deleteButton.innerText = "X";
deleteButton.addEventListener("click", function() {
this.parentElement.style.display = 'none';
});
// Configure the check box
var checkBox = document.createElement("input");
checkBox.id = "check";
checkBox.type = 'checkbox';
checkBox.addEventListener('change', function() {
labelText.style.textDecoration = checkBox.checked ? 'line-through' : 'none';
});
// Configure the label
var label = document.createElement("label");
var labelText = document.createElement("span");
labelText.innerText = input.value;
// Put the checkbox and label text in to the label element
label.appendChild(checkBox);
label.appendChild(labelText);
// Put the label (with the checkbox inside) and the delete
// button into the list item.
listItem.appendChild(label);
listItem.appendChild(deleteButton);
list.appendChild(listItem);
inputItem.focus();
inputItem.select();
return false;
}
localStorage.setItem("list", list);
localStorage.getItem("list").forEach(function(list) {
elem.textContent = list;
});
</script>
</body>
</html>
We meet again. Part of the problem was that you were centering everything which was throwing off your styles. I removed the centering except on your #outerDiv. Then, I put a little bit of margin to the right of the checkbox so they wouldn't sit too close to each other. Finally, the button I floated to the right so that they will always all be right aligned.
var inputItem = document.getElementById("inputItem");
inputItem.focus();
// adds input Item to list
function addItem(list, input) {
var inputItem = this.inputItem;
var list = document.getElementById(list);
var listItem = document.createElement("li");
// Configure the delete button
var deleteButton = document.createElement("button");
deleteButton.innerText = "X";
deleteButton.addEventListener("click", function() {
this.parentElement.style.display = 'none';
});
// Configure the check box
var checkBox = document.createElement("input");
checkBox.id = "check";
checkBox.type = 'checkbox';
checkBox.addEventListener('change', function() {
labelText.style.textDecoration = checkBox.checked ? 'line-through' : 'none';
});
// Configure the label
var label = document.createElement("label");
var labelText = document.createElement("span");
labelText.innerText = input.value;
// Put the checkbox and label text in to the label element
label.appendChild(checkBox);
label.appendChild(labelText);
// Put the label (with the checkbox inside) and the delete
// button into the list item.
listItem.appendChild(label);
listItem.appendChild(deleteButton);
list.appendChild(listItem);
inputItem.focus();
inputItem.select();
return false;
}
//localStorage.setItem("list", list);
//localStorage.getItem("list").forEach(function(list) {
// elem.textContent = list;
//});
body {}
form {
display: inline-block;
}
#outerDiv {
padding: 30px;
text-align: center;
}
#innerDiv {
margin: auto;
width: 200px;
height: 100px;
}
ul {
padding: 0;
margin: 0;
}
ul li {
position: relative;
padding: 12px 8px 12px 20px;
background: rgb(148, 160, 181);
list-style-type: none;
font-size: 18px;
}
#submit {
position: absolute;
padding: 10px 16px;
}
/* Style the input */
button {
float: right;
}
input {
margin: 0;
border: none;
border-radius: 0;
padding: 10px;
float: left;
font-size: 16px;
margin-right: 8px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<h1 align="center"> To-Do List </h1>
<body>
<div id="outerDiv">
<form onsubmit="return addItem('list', this.inputItem)">
<input type="text" id="inputItem" onfocus="this.value=''" onselect="this.value=''" placeholder="Enter a Task">
<input id="submit" type="submit">
</form>
</div>
<div id="innerDiv">
<ul id="list"></ul>
</div>
</body>
</html>
I have created a few new classes for you in the css, they are in the working snippet under #innerDiv. (Also a tip, you don't need to add in the css and script into the html file in the snippet). Hope that helps!
var inputItem = document.getElementById("inputItem");
inputItem.focus();
// adds input Item to list
function addItem(list, input) {
var inputItem = this.inputItem;
var list = document.getElementById(list);
var listItem = document.createElement("li");
// Configure the delete button
var deleteButton = document.createElement("button");
deleteButton.innerText = "X";
deleteButton.addEventListener("click", function() {
this.parentElement.style.display = 'none';
});
// Configure the check box
var checkBox = document.createElement("input");
checkBox.id = "check";
checkBox.type = 'checkbox';
checkBox.addEventListener('change', function() {
labelText.style.textDecoration = checkBox.checked ? 'line-through' : 'none';
});
// Configure the label
var label = document.createElement("label");
var labelText = document.createElement("span");
labelText.innerText = input.value;
// Put the checkbox and label text in to the label element
label.appendChild(checkBox);
label.appendChild(labelText);
// Put the label (with the checkbox inside) and the delete
// button into the list item.
listItem.appendChild(label);
listItem.appendChild(deleteButton);
list.appendChild(listItem);
inputItem.focus();
inputItem.select();
return false;
}
//localStorage.setItem("list", list);
//localStorage.getItem("list").forEach(function(list) {
// elem.textContent = list;
//});
body {
text-align: center;
}
form {
display: inline-block;
}
#outerDiv {
padding: 30px;
text-align: center;
}
#innerDiv {
margin: auto;
width: 200px;
height: 100px;
}
#innerDiv button {
margin: 0 5px;
padding: 2px;
position: absolute;
right: 0;
}
#innerDiv li {
margin: 0;
padding: 4px 0px 0px 4px;
text-align: left;
}
#innerDiv label {
padding-left: 4px;
}
ul {
padding: 0;
margin: 0;
}
ul li {
position: relative;
padding: 12px 8px 12px 40px;
background: rgb(148, 160, 181);
list-style-type: none;
font-size: 18px;
}
#submit {
position: absolute;
padding: 10px 16px;
}
/* Style the input */
input {
margin: 0;
border: none;
border-radius: 0;
padding: 10px;
float: left;
font-size: 16px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<h1 align="center"> To-Do List </h1>
<body>
<div id="outerDiv">
<form onsubmit="return addItem('list', this.inputItem)">
<input type="text" id="inputItem" onfocus="this.value=''" onselect="this.value=''" placeholder="Enter a Task">
<input id="submit" type="submit">
</form>
</div>
<div id="innerDiv">
<ul id="list"></ul>
</div>
</body>
</html>
First add a class to the delete button
deleteButton.classList.add("delete-button");
Than style the button using that class as much as you wish in your CSS.
** You have to work on your todo text also. If the text is longer, the style breaks. You can apply same technique here - add a class with JS, style that class in CSS.
var inputItem = document.getElementById("inputItem");
inputItem.focus();
// adds input Item to list
function addItem(list, input) {
var inputItem = this.inputItem;
var list = document.getElementById(list);
var listItem = document.createElement("li");
// Configure the delete button
var deleteButton = document.createElement("button");
deleteButton.classList.add("delete-button");
deleteButton.innerText = "X";
deleteButton.addEventListener("click", function() {
this.parentElement.style.display = 'none';
});
// Configure the check box
var checkBox = document.createElement("input");
checkBox.id = "check";
checkBox.type = 'checkbox';
checkBox.addEventListener('change', function() {
labelText.style.textDecoration = checkBox.checked ? 'line-through' : 'none';
});
// Configure the label
var label = document.createElement("label");
var labelText = document.createElement("span");
labelText.innerText = input.value;
// Put the checkbox and label text in to the label element
label.appendChild(checkBox);
label.appendChild(labelText);
// Put the label (with the checkbox inside) and the delete
// button into the list item.
listItem.appendChild(label);
listItem.appendChild(deleteButton);
list.appendChild(listItem);
inputItem.focus();
inputItem.select();
return false;
}
localStorage.setItem("list", list);
localStorage.getItem("list").forEach(function(list) {
elem.textContent = list;
});
body {
text-align: center;
}
form {
display: inline-block;
}
#outerDiv {
padding: 30px;
text-align: center;
}
#innerDiv {
margin: auto;
width: 200px;
height: 100px;
}
ul {
padding: 0;
margin: 0;
}
ul li {
position: relative;
padding: 12px 8px 12px 40px;
background: rgb(148, 160, 181);
list-style-type: none;
font-size: 18px;
}
#submit {
position: absolute;
padding: 10px 16px;
}
/* Style the input */
input {
margin: 0;
border: none;
border-radius: 0;
padding: 10px;
float: left;
font-size: 16px;
}
.delete-button {
float: right;
border: 0;
padding: 1px 3px 0;
font-size: 9px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<h1 align="center"> To-Do List </h1>
<body>
<div id="outerDiv">
<form onsubmit="return addItem('list', this.inputItem)">
<input type="text" id="inputItem" onfocus="this.value=''" onselect="this.value=''" placeholder="Enter a Task">
<input id="submit" type="submit">
</form>
</div>
<div id="innerDiv">
<ul id="list"></ul>
</div>
<script>
var inputItem = document.getElementById("inputItem");
inputItem.focus();
// adds input Item to list
function addItem(list, input) {
var inputItem = this.inputItem;
var list = document.getElementById(list);
var listItem = document.createElement("li");
// Configure the delete button
var deleteButton = document.createElement("button");
deleteButton.innerText = "X";
deleteButton.addEventListener("click", function() {
this.parentElement.style.display = 'none';
});
// Configure the check box
var checkBox = document.createElement("input");
checkBox.id = "check";
checkBox.type = 'checkbox';
checkBox.addEventListener('change', function() {
labelText.style.textDecoration = checkBox.checked ? 'line-through' : 'none';
});
// Configure the label
var label = document.createElement("label");
var labelText = document.createElement("span");
labelText.innerText = input.value;
// Put the checkbox and label text in to the label element
label.appendChild(checkBox);
label.appendChild(labelText);
// Put the label (with the checkbox inside) and the delete
// button into the list item.
listItem.appendChild(label);
listItem.appendChild(deleteButton);
list.appendChild(listItem);
inputItem.focus();
inputItem.select();
return false;
}
localStorage.setItem("list", list);
localStorage.getItem("list").forEach(function(list) {
elem.textContent = list;
});
</script>
</body>
</html>