So I'm a newb at web dev, and trying to get my head around JavaScript by writing a.. yeah, you guessed it, a to do list.
I've been trying to set the items to the local storage, and then retrieve it, it sorta works, however when the list items are retrieved, the buttons do not seem to function, and I can't for the life of me figure out why... Any thoughts?
Here's the code:
document.addEventListener('DOMContentLoaded', () => {
const submitButton = document.querySelector('.submit');
submitButton.type = 'submit';
const inputField = document.querySelector('.createItem');
const toDoUl = document.querySelector('.toDoUl');
const completedUl = document.querySelector('.completedUl');
const form = document.querySelector('#header');
const tdContainer = document.getElementById('tdContainer');
const toDoItems = document.getElementById('toDoItems');
(function loadStorage() {
if (localStorage.getItem('todo')) {
tdContainer.innerHTML = localStorage.getItem('todo');
}
})();
function noChildren() {
if (toDoUl.hasChildNodes()) {
tdContainer.classList.remove('tdContainer');
} else {
tdContainer.className = 'tdContainer';
}
}
function createLi() {
const wrapper = document.getElementById('wrapper');
const doneButton = document.createElement('input');
const checkedLabel = document.createElement('label');
doneButton.type = 'checkbox';
checkedLabel.className = 'done';
checkedLabel.appendChild(doneButton);
const listItem = document.createElement('li');
const p = document.createElement('p');
const editButton = document.createElement('button');
const removeButton = document.createElement('button');
toDoUl.appendChild(listItem);
p.textContent = inputField.value;
inputField.value = '';
editButton.className = 'edit';
removeButton.className = 'remove';
listItem.appendChild(checkedLabel);
listItem.appendChild(p);
listItem.appendChild(editButton);
listItem.appendChild(removeButton);
doneButton.style.display = 'none';
editButton.addEventListener('click', () => {
listItem.contentEditable = 'true';
});
listItem.addEventListener('blur', () => {
listItem.contentEditable = 'false';
});
removeButton.addEventListener('click', e => {
const ul = e.target.parentNode.parentNode;
/*const li = e.target.parentNode.parentNode;*/
ul.removeChild(e.target.parentNode);
noChildren();
});
doneButton.addEventListener('click', e => {
if (e.target.parentNode.parentNode.parentNode.className === 'toDoUl') {
completedUl.appendChild(e.target.parentNode.parentNode);
e.target.parentNode.parentNode.className = 'removeTransition';
noChildren();
localStorage.setItem('todo', tdContainer.innerHTML);
} else {
toDoUl.appendChild(e.target.parentNode.parentNode);
e.target.parentNode.parentNode.className = 'addTransition';
noChildren();
}
});
}
form.addEventListener('submit', e => {
e.preventDefault();
noChildren();
createLi();
localStorage.setItem('todo', tdContainer.innerHTML);
});
});
You can see the working version here: http://kozyrev.site/todo/
i'm glad you're writing arrow functions and cool stuff :D
but it seems that you are setting event listeners within createLi function, that is dispatched on form's submit event.
But, when you loads localStorage, is setting HTML content like this:
tdContainer.innerHTML = localStorage.getItem('todo');
event listener is not attached to them, because all of these elements that you created from localStorage, is not create by createLi function :(
but you might write something like this:
// loads from localStorage
(function loadStorage() {
if (localStorage.getItem('todo')) {
tdContainer.innerHTML = localStorage.getItem('todo');
}
})();
// set listeners below
var liSelector = '.toDoUl > li'
var liElements = document.querySelectorAll(liSelector)
Array.prototype.forEach.call(liElements, (liElement) => {
var editButton = liElement.querySelector('.edit')
console.log(editButton)
// you can set listeners here
editButton.addEventListener('click', (e) => {
e.preventDefault()
console.log('yey, event has dispatched, do your magic :)')
})
})
UPDATE: example using named function to reuse them:
function createLi() {
....
const listItem = document.createElement('li');
....
editButton.addEventListener('click', () => {
listItem.contentEditable = 'true';
});
could be written like this
// this function at top of script
const setEditable = (listItem) => {
listItem.contentEditable = 'true';
}
// you can use setEditable within createLi
function createLi() {
....
const listItem = document.createElement('li');
....
editButton.addEventListener('click', () => {
setEditable(listItem)
});
also, after HTML was written from localStorage like this
// loads from localStorage
(function loadStorage() {
if (localStorage.getItem('todo')) {
tdContainer.innerHTML = localStorage.getItem('todo');
}
})();
// set listeners below
var liSelector = '.toDoUl > li'
var liElements = document.querySelectorAll(liSelector)
Array.prototype.forEach.call(liElements, (listItem) => {
var editButton = listItem.querySelector('.edit')
// you can set listeners here
editButton.addEventListener('click', (e) => {
setEditable(listItem)
})
})
I didn't tested, but i hope it works, and it's shows you that named function could be reused for setting listeners :)
Related
I'm new to javascript and I am trying to use local storage to save user input. With the code as it is right now, I get the user input saved to local storage, but the list does not save when refreshing the page. Also, the user input appends to the to do list multiple times. Thanks for taking a look.
window.addEventListener('load', () => {
const form = document.querySelector('#new-task-form');
const input = document.querySelector('#new-task-input');
const listElement = document.querySelector('#tasks');
todos = JSON.parse(localStorage.getItem('todos')) || [];
console.log(todos)
form.addEventListener('submit', (e) => {
e.preventDefault();
const task = input.value;
if(!task) {
alert('You definitely have something to do...')
return
}
const todo = {
content: task,
id: Math.floor(Math.random() * 100000)
}
todos.push(todo);
localStorage.setItem('todos', JSON.stringify(todos));
todos.forEach(todo => {
const taskElement = document.createElement('div');
taskElement.classList.add('task');
const taskContentElement = document.createElement('div');
taskContentElement.classList.add("content");
taskElement.appendChild(taskContentElement);
const taskInputElement = document.createElement("input")
taskInputElement.classList.add("text");
taskInputElement.type = "text";
taskInputElement.value = task;
taskInputElement.setAttribute('readonly', 'readonly');
taskContentElement.appendChild(taskInputElement);
const taskActionsElement = document.createElement('div');
taskActionsElement.classList.add("actions");
const taskEditElement = document.createElement('button');
taskEditElement.classList.add('edit');
taskEditElement.innerHTML = "Edit";
const taskDeleteElement = document.createElement('button');
taskDeleteElement.classList.add('delete');
taskDeleteElement.innerHTML = "Delete";
taskActionsElement.appendChild(taskEditElement);
taskActionsElement.appendChild(taskDeleteElement);
taskElement.appendChild(taskActionsElement);
listElement.appendChild(taskElement);
input.value = '';
taskEditElement.addEventListener('click', () => {
if (taskEditElement.innerText.toLowerCase() == 'edit') {
taskInputElement.removeAttribute('readonly');
taskInputElement.focus();
taskEditElement.innerText = "Save";
localStorage.setItem("todos", JSON.stringify(todos));
} else {
taskInputElement.setAttribute('readonly', 'readonly');
taskEditElement.innerText = 'Edit';
}
});
taskDeleteElement.addEventListener('click', () => {
todos = todos.filter(t => t != todo);
localStorage.setItem('todos', JSON.stringify(todos));
listElement.removeChild(taskElement);
});
});
});
});
The user input comes up multiple times when added to the list, depending on when added to the array. I was hoping for it to come up one time, and for it to be a normal list.
So i'm trying to remove my classlist of selected items when they are clicked again:
const todo = []
const elements = []
const todoList = document.getElementById('todoList')
const addItem = document.getElementById('textBox')
const submit = document.getElementById('submit')
const todoListItem = document.querySelectorAll('.todoListItem')
const todoListItemArr = Array.from(todoListItem)
const deleteItem = document.getElementById('deleteButton')
let selected
class Div {
constructor(content) {
this.content = content
}
addToScreen(){
const element = document.createElement('div')
element.innerHTML = this.content
element.classList.add('todoListItem')
todoList.appendChild(element)
}
select(){
const element = document.querySelectorAll('.todoListItem')
element.forEach(item => {
item.addEventListener('click', () => {
item.classList.add('selectedItem')
selected = item
})
})
}
deselect() {
const elements = document.querySelectorAll('.selectedItem')
elements.forEach(item => {
item.addEventListener('click', () => {
item.classList.remove('selectedItem')
})
})
}
}
function createItem() {
const todoItem = new Div(addItem.value)
todoItem.addToScreen()
todo.push(todoItem.content)
console.log(todo)
addItem.value = ''
todoItem.select()
todoItem.deselect()
}
addItem.addEventListener('keypress', (e) => {
if(e.key == 'Enter') {
createItem()
}
})
submit.addEventListener('click', createItem)
also I'm trying to add a delete function, but everytime i try to remove the element in the constructor by adding a delete function, my delete button does nothing, i've removed those features for now.
I am doing some practice javascript exercise. My project look like 'trello' but much soft and simple.
When i writing some notes to input, javscript adding note dynamically but if i refresh the page/chrome, all things gone or lost.
So i wanna apply localstorage on my project. How can i do it.
My Note project: https://codepen.io/daniel_134/pen/NWwYKyK[My Note project]1
var input = document.querySelector('#text-input');
document.querySelector("#ad-note-btn").addEventListener("click", () => {
if (input.value.length > 1) {
// GET-INPUT-VALUE
var getvalue = input.value;
// CREATE-NEW-NOTE
const newLi = document.createElement("textarea");
newLi.value = getvalue;
newLi.className = "note-li";
// ADD-NEW-NOTE
var ul = document.querySelector('#list-items');
ul.appendChild(newLi);
// EMPTY-INPUT-WHEN-CREATING-NEW-NOTES
input.value = " ";
// DELETE-NOTES
const dleLi = document.createElement("button");
dleLi.textContent = "delete";
dleLi.className = "list-btn";
ul.appendChild(dleLi);
dleLi.addEventListener("click", () => {
newLi.remove();
dleLi.remove();
edLi.remove();
saveLi.remove();
})
// EDIT-NOTES
const edit = () => {
if( newLi.value.length > 0 ) {
newLi.disabled = true;
} else {
newLi.disabled = false;
}
}
edit()
const edLi = document.createElement("button");
edLi.textContent = "Edit";
ul.appendChild(edLi);
edLi.className = "list-btn";
edLi.addEventListener("click", () => {
if ( newLi.disabled = true ) {
newLi.disabled = false;
}else {
newLi.disabled = true;
}
})
const saveLi = document.createElement("button");
saveLi.textContent = "save";
ul.appendChild(saveLi);
saveLi.className = "list-btn";
saveLi.addEventListener("click", () => {
edit();
})
} else {
ul.appendChild();
}
})
document.querySelector("#clear-btn").addEventListener("click", () => {
input.value = " ";
})
2
it'll look like that , for example :
when you load your page .
load todoList var todoList = JSON.parse(localStorage.getItem('todo-list'))
and display it
when you add new element to your to-do list
var todoList = JSON.parse(localStorage.getItem('todo-list'));
var new_todo = [{
title:'for example ...',
complete:false
}];
localStorage.setItem('todo-list',JSON.stringify(new_todo));
}else{
todoList.push({
title:'for example ...',
complete:false
});
localStorage.setItem('todo-list',JSON.stringify(todoList));
}
I would like to shorten this code, but can't figure out how.
The code works in the way that when you press the button in the selector, a map point and a text on the bottom of the map appear. It works in this way it is, but I am sure that there is a way to shorten it. I just have not enough knowledge on how to shorten it.
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('.select__item').forEach( function(tabBtn) {
tabBtn.addEventListener('click', function(event) {
const path = event.currentTarget.dataset.path
document.querySelectorAll('.sketch__item',).forEach( function(tabContent) {
tabContent.classList.remove('block-active')
})
document.querySelectorAll('.details__item',).forEach( function(tabContent) {
tabContent.classList.remove('block-active')
})
document.querySelectorAll(`[data-target="${path}"]`).forEach( function(tabsTarget) {
tabsTarget.classList.add('block-active')
})
})
})
//*** tabs active
let tabsChange = document.querySelectorAll('.select__item')
tabsChange.forEach(button => {
button.addEventListener('click', function () {
tabsChange.forEach(btn => btn.classList.remove('active__tab'))
this.classList.add('active__tab')
})
})
})
let select = function () {
let selectHeader = document.querySelectorAll('.select__header');
let selectItem = document.querySelectorAll('.select__item');
selectHeader.forEach(item => {
item.addEventListener('click', selectToggle)
});
selectItem.forEach(item => {
item.addEventListener('click', selectChoose)
});
function selectToggle() {
this.parentElement.classList.toggle('is-active');
}
function selectChoose() {
let text = this.innerText,
select = this.closest('.partner__select'),
currentText = select.querySelector('.select__current');
currentText.innerText = text;
select.classList.remove('is-active');
}
};
//*** Tabs
select();
Delegation shortens the code.
If you delegate, you shorten the code. Never loop eventlisteners in a container. Use the container instead
I lost 20 lines and made code easier to debug
NOTE: I did not have your HTML so I may have created some errors or logic issues you will need to tackle
const selectChoose = e => {
const tgt = e.target;
let text = tgt.innerText,
select = tgt.closest('.partner__select'),
currentText = select.querySelector('.select__current');
currentText.innerText = text;
select.classList.remove('is-active');
};
const selectToggle = e => e.target.parentElement.classList.toggle('is-active');
window.addEventListener('load', function() {
const container = document.getElementById('container');
container.addEventListener('click', e => {
const tgt = e.target.closest('.select');
if (tgt) {
const path = tgt.dataset.path;
document.querySelectorAll('.item', ).forEach(tabContent => tabContent.classList.remove('block-active'))
document.querySelectorAll(`[data-target="${path}"]`).forEach(tabsTarget => tabsTarget.classList.add('block-active'))
}
})
const tabContainer = document.getElementById('tabContainer');
//*** tabs active
tabContainer.addEventListener('click', e => {
const tgt = e.target.closest('button');
if (tgt) {
tabContainer.querySelectorAll('.active__tab').forEach(tab => tabclassList.remove('active__tab'))
tgt.classList.add('active__tab')
}
}) const selContainer = document.getElementById('selectContainer');
selContainer.addEventListener('click', e => {
const tgt = e.target;
if (tgt.classList.contains('select__header')) selectToggle(e);
else if (tgt.classList.contains('select__item')) selectChoose(e)
})
})
I am pretty much new to Javascript and working on this simple ToDo app that uses local storage to persist data. However, the Delete function can only delete from local storage when refreshed the page. What could be causing this bug? I have attached my code below
I tried commenting on the e.preventDefault() on the form but the page kept on reloading when a task is submitted.
// Selectors
const ul = document.querySelector('.todo-list');
const todoContainer = document.querySelector('.todo-container');
const clearButton = document.createElement('button');
clearButton.classList.add('clear-button');
clearButton.textContent = 'Clear all Completed';
const form = document.querySelector('.form');
const taskInput = document.querySelector('.todo-input');
let todoTasks = JSON.parse(localStorage.getItem('todo')) || [];
let id = todoTasks.length + 1;
const createElement = ({ description, completed = true, index }) => {
const todoItem = document.createElement('li');
todoItem.classList.add('todo-list-item');
todoItem.setAttribute('id', index);
todoItem.innerHTML = `
<input type="checkbox" class="check" value="${completed}">
<button class="hidden" name="${index}"></button>
<span class="todo-item">${description}</span>
<button name='eclips'><i class="fas fa-ellipsis-v"></i></button>
<button name='delete'><i class="fas fa-trash"></i></button>
`;
ul.appendChild(todoItem);
todoContainer.appendChild(ul);
todoContainer.appendChild(clearButton);
};
// get each todo task
todoTasks.forEach(createElement);
// Function that add todo
const addTask = (description, completed, ind) => {
const input = taskInput.value;
todoTasks.push({
description: input,
completed: false,
index: ind,
});
localStorage.setItem('todo', JSON.stringify(todoTasks));
return { description, completed, ind };
};
const checkTodo = (e) => {
const lineText = e.target.nextElementSibling.nextElementSibling.nextElementSibling;
if (lineText.style.textDecoration === 'line-through') {
lineText.style.textDecoration = 'none';
} else {
lineText.style.textDecoration = 'line-through';
lineText.classList.toggle('completed');
}
};
// Function that delete todo
const handleDeleteAndCheck = (e) => {
const item = e.target;
if (e.target.classList[1] === 'fa-trash') {
const todo = item.parentElement.parentElement;
const targetId = item.parentElement.parentElement.id;
todoTasks = todoTasks.filter((task) => task.index !== +targetId);
localStorage.setItem('todo', JSON.stringify(todoTasks));
todo.remove();
}
if (e.target.classList === 'check') {
checkTodo();
}
};
// Function that Edit todo
const editTask = (e) => {
const item = e.target;
if (item.classList[0] === 'todo-item') {
item.contentEditable = true;
item.style.display = 'block';
}
};
const check = document.querySelectorAll('.fa-check-square');
const index = document.querySelectorAll('#index');
form.addEventListener('submit', (e) => {
e.preventDefault();
const input = taskInput.value;
const checkValue = check.value;
// const indexValue = index.value;
const newTask = addTask(input, checkValue, id);
createElement(newTask);
// location.reload();
taskInput.value = '';
id += 1;
});
ul.addEventListener('click', handleDeleteAndCheck);
ul.addEventListener('click', editTask);
Here please change the statement with this in your handleDeleteAndCheck() method. It will remove the local storage at that time.
localStorage.removeItem('todo');