How to edit array item using javascript - javascript

I am pretty new to js. I am trying to complete a todo sort of app. I have been able to create, render and delete an array item, but I am having trouble editing.
All these operations are done with the uuidv4 library to generate an id for each array item created.
With an individual id selected for an array item, I am generating dynamic buttons, one for deleting the array item, the other one for editing.
Upon clicking edit, I want to open up a modal that contains the content of the selected array item. After making the changes, the edit button inside the modal should call upon an edit function to update the changes and then rerender the array.
My issue is that I can't open up the modal dialog box when clicking the edit button.
This is the code to create the necessary structure, the code for creating, rendering and deleting is not included as they are working properly.
// Generate the DOM structure for a todo
const generateTodoDOM = function(todo) {
const todoEl = document.createElement("div");
const checkbox = document.createElement("input");
const label = document.createElement("label");
checkbox.appendChild(label);
todoEl.setAttribute("id", "myTodos");
const textEl = document.createElement("p");
const editButton = document.createElement("button");
editButton.setAttribute("id", "modal-btn");
const removeButton = document.createElement("button");
const createDate = document.createElement("p");
createDate.textContent = `Created: ${dateCreated}`;
createDate.style.color = "#956E93";
// Setup the todo text
textEl.textContent = todo.text;
todoEl.appendChild(textEl);
// Setup the remove button
removeButton.textContent = "x";
todoEl.appendChild(removeButton);
removeButton.addEventListener("click", function() {
removeTodo(todo.id);
saveTodos(todos);
renderTodos(todos, filters);
});
// TODO: Setup the edit note button
editButton.textContent = "Edit Todo";
todoEl.appendChild(editButton);
editButton.addEventListener("click", function() {
//Launch the modal
editModal(todo.id);
});
// Setup todo checkbox
checkbox.setAttribute("type", "checkbox");
checkbox.checked = todo.completed;
todoEl.appendChild(checkbox);
checkbox.addEventListener("change", function() {
toggleTodo(todo.id);
saveTodos(todos);
renderTodos(todos, filters);
});
todoEl.appendChild(createDate);
return todoEl;
};
The code for the modal is the following:
//Edit modal todo by id
const editModal = function(id) {
const todoIndex = todos.findIndex(function(todo) {
return todo.id === id;
});
if (todoIndex > -1) {
const modal = document.querySelector("#my-modal");
const modalBtn = document.querySelector("#modal-btn");
const editTodoContentBtn = document.querySelector("#submitEditTodo")
const closeBtn = document.querySelector(".close");
// Events
modalBtn.addEventListener("click", openModal);
closeBtn.addEventListener("click", closeModal);
editTodoContentBtn.addEventListener("click", editTodo)
window.addEventListener("click", outsideClick);
// Open
function openModal() {
modal.style.display = "block";
}
// Close
function closeModal() {
modal.style.display = "none";
}
// Close If Outside Click
function outsideClick(e) {
if (e.target == modal) {
modal.style.display = "none";
}
}
//Edit the content of the textarea
function editTodo(e) {
editTodo(id)
}
}
};
When clicking the submitEditTodo button the following edit function should be fired:
//Edit todo by id
const editTodo = function(id) {
const editTodoContent = document.querySelector('#editTodo')
const todoIndex = todos.findIndex(function(todo) {
return todo.id === id;
});
if (todoIndex > -1) {
editTodoContent.value = todos.text
saveTodos(todos)
renderTodos(todos, filters);
}
};
The saveTodos and renderTodos are functioning properly with other functions for creating, rendering and deleting.
This is the HTML code:
<!-- Edit modal -->
<div id="my-modal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>Edit Todo</h2>
</div>
<div class="modal-body">
<textarea name="" class="editTextArea" id="editTodo" rows="10"></textarea>
<button class="button" id="submitEditTodo">Edit Todo</button>
</div>
<div class="modal-footer">
<!-- <h3>Modal Footer</h3> -->
</div>
</div>
<!-- End modal -->
and this is the CSS for the modal:
/*
Edit todo modal start
*/
:root {
--modal-duration: 1s;
--modal-color: #BB8AB8;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
height: 100%;
width: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
margin: 10% auto;
width: 35%;
box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
animation-name: modalopen;
animation-duration: var(--modal-duration);
}
.editTextArea{
width:100%
}
.modal-header h2,
.modal-footer h3 {
margin: 0;
}
.modal-header {
background: var(--modal-color);
padding: 15px;
color: #fff;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
.modal-body {
padding: 10px 20px;
background: #fff;
}
.modal-footer {
background: var(--modal-color);
padding: 10px;
color: #fff;
text-align: center;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
}
.close {
color: #ccc;
float: right;
font-size: 30px;
color: #fff;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
#keyframes modalopen {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/*
Edit todo modal end
*/
Thanks

Below are a few pointers to where you might need adjustments to achieve what you want.
Currently you are adding new listeners to the modal every time you click an edit button for a todo. This should probably only be set once. Alternatively you should remove the listeners when the modal is closed.
Your function editModal does not actually open the modal. What it does is add a listener to the #modal-btn button which will then open the modal the next time you click the button.
You are setting id's for both the outer div and the edit button, but the id's are not based on anything related to the todo element you are creating. So effectively all those elements end up with the same id. An id (short for identifier) is usually meant to be unique. For grouping of multiple elements you should instead use the class attribute.
Your function "editTodo" calls itself. Recursing indefinitely. Beware of reusing function names.
With that said the below code is a crude way to do what I think you want to do based on the snippets you provided:
// Open
const openModal = function() {
document.querySelector("#my-modal").style.display = "block";
}
// Close
const closeModal = function() {
document.querySelector("#my-modal").style.display = "none";
}
function initModal() {
const modal = document.querySelector("#my-modal");
const closeBtn = document.querySelector(".close");
// Events
closeBtn.addEventListener("click", closeModal);
window.addEventListener("click", outsideClick);
// Close If Outside Click
function outsideClick(e) {
if (e.target == modal) {
modal.style.display = "none";
}
}
}
const filters = []; // dummy variable
// Generate the DOM structure for a todo
var todos = []
function generateTodoDOM(todo) {
todos.push(todo);
const todoEl = document.createElement("div");
const checkbox = document.createElement("input");
const label = document.createElement("label");
checkbox.appendChild(label);
todoEl.setAttribute("id", "my-todos-" + todo.id);
const textEl = document.createElement("p");
const editButton = document.createElement("button");
editButton.setAttribute("id", "modal-btn-" + todo.id);
const removeButton = document.createElement("button");
const createDate = document.createElement("p");
createDate.textContent = 'Created: ' + new Date();
createDate.style.color = "#956E93";
// Setup the todo text
textEl.textContent = todo.text;
todoEl.appendChild(textEl);
// Setup the remove button
removeButton.textContent = "x";
todoEl.appendChild(removeButton);
removeButton.addEventListener("click", function() {
removeTodo(todo.id);
saveTodos(todos);
renderTodos(todos, filters);
});
// TODO: Setup the edit note button
editButton.textContent = "Edit Todo";
todoEl.appendChild(editButton);
editButton.addEventListener("click", function() {
//Launch the modal
editModal(todo.id);
openModal();
});
// Setup todo checkbox
checkbox.setAttribute("type", "checkbox");
checkbox.checked = todo.completed;
todoEl.appendChild(checkbox);
checkbox.addEventListener("change", function() {
toggleTodo(todo.id);
saveTodos(todos);
renderTodos(todos, filters);
});
todoEl.appendChild(createDate);
return todoEl;
};
var editFn
//Edit modal todo by id
const editModal = function(id) {
const todoIndex = todos.findIndex(function(todo) {
return todo.id === id;
});
if (todoIndex > -1) {
const modal = document.querySelector("#my-modal");
const editElm = document.querySelector("#editTodo");
const editTodoContentBtn = document.querySelector("#submitEditTodo")
editElm.value = todos[todoIndex].text;
// Events
editTodoContentBtn.removeEventListener("click", editFn)
//Edit the content of the textarea
editFn = function(e) {
editTodo(id)
closeModal()
}
editTodoContentBtn.addEventListener("click", editFn)
}
};
//Edit todo by id
const editTodo = function(id) {
const editTodoContent = document.querySelector('#editTodo')
const todoIndex = todos.findIndex(function(todo) {
return todo.id === id;
});
if (todoIndex > -1) {
todos[todoIndex].text = editTodoContent.value;
saveTodos(todos)
renderTodos(todos, filters);
}
};
const saveTodos = function(todos) {
// dummy method, we're keeping it in memory for this example
}
const renderTodos = function(todosToRender) {
todos = []; // clear current in-memory array
var todoList = document.getElementById("todo-container");
while (todoList.firstChild) {
todoList.removeChild(todoList.firstChild);
}
for(var i = 0; i < todosToRender.length; i++) {
todoList.appendChild(generateTodoDOM(todosToRender[i]));
}
};
initModal();
const container = document.getElementById("todo-container");
var generatedTodos = [];
for(var i = 0; i < 10; i++) {
var todo = { text: "Todo " + (i+1), id: "todo-" + i, completed: false};
generatedTodos.push(todo);
}
renderTodos(generatedTodos);
/*
Edit todo modal start
*/
:root {
--modal-duration: 1s;
--modal-color: #BB8AB8;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
height: 100%;
width: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
margin: 10% auto;
width: 35%;
box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
animation-name: modalopen;
animation-duration: var(--modal-duration);
}
.editTextArea{
width:100%
}
.modal-header h2,
.modal-footer h3 {
margin: 0;
}
.modal-header {
background: var(--modal-color);
padding: 15px;
color: #fff;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
.modal-body {
padding: 10px 20px;
background: #fff;
}
.modal-footer {
background: var(--modal-color);
padding: 10px;
color: #fff;
text-align: center;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
}
.close {
color: #ccc;
float: right;
font-size: 30px;
color: #fff;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
#keyframes modalopen {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/*
Edit todo modal end
*/
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="todo-container">
</div>
<!-- Edit modal -->
<div id="my-modal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>Edit Todo</h2>
</div>
<div class="modal-body">
<textarea name="" class="editTextArea" id="editTodo" rows="10"></textarea>
<button class="button" id="submitEditTodo">Edit Todo</button>
</div>
<div class="modal-footer">
<!-- <h3>Modal Footer</h3> -->
</div>
</div>
</div>
<!-- End modal -->
</body>
</html>

Related

JavaScript modal will only close after the first time opening it but not after the second time

I'm making a note taker app that gives you the option to view said note in a modal whenever the button is clicked. There are two ways the close it by clicking the "X" button or by clicking outside of the modal.
When I proceed with one of these options, the modal will close successfully, but if I open it a second time neither the "X" button or clicking outside seem to work. How could I fix this problem?
class Input {
constructor(note) {
this.note = note;
}
}
class UI {
addNote(input) {
// Get table body below form
const content = document.querySelector(".content");
// Create tr element
const row = document.createElement("tr");
// Insert new HTML into div
row.innerHTML = `
<td>
${input.note}
<br><br>
<button class="modalBtn">View Note</button>
</td>
`;
content.appendChild(row);
// Event listener to make modal
document.querySelector(".modalBtn").addEventListener("click", function(e) {
// Get container div
const container = document.querySelector(".container");
// Create div
const div = document.createElement("div");
// Assign class to it
div.className = "modal";
// Insert HTML into div
div.innerHTML = `
<div class="modal-content">
<span class="closeBtn">×</span>
<div>
<p>${input.note}</p>
</div>
</div>
`;
// Append the new div to the container div
container.appendChild(div);
// Get modal
const modal = document.querySelector(".modal");
// Event listener to close modal when "x" is clicked
document.querySelector(".closeBtn").addEventListener("click", function() {
modal.style.display = "none";
});
// Event listener to close when the window outside the modal is clicked
window.addEventListener("click", function(e) {
if (e.target === modal) {
modal.style.display = "none";
}
});
});
}
// Clear input field
clearInput() {
note.value = "";
}
}
// Event listener for addNote
document.getElementById("note-form").addEventListener("submit", function(e) {
// Get form value
const note = document.getElementById("note").value;
// Instantiate note
const input = new Input(note);
// Instantiate UI
const ui = new UI();
// Validate form (make sure input is filled)
if (note === "") {
// Error alert
alert("Please fill in text field!");
}
else {
// Add note
ui.addNote(input);
// Clear input field
ui.clearInput();
}
e.preventDefault();
});
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 17px;
line-height: 1.6;
}
.button {
background: coral;
padding: 1em 2em;
color: #fff;
border: 0;
}
.button:hover {
background: #333;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
height: 100%;
width: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
background-color: #f4f4f4;
margin: 20% auto;
padding: 20px;
width: 70%;
box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.17);
animation-name: modalopen;
animation-direction: 1s;
}
.closeBtn {
color: #ccc;
float: right;
font-size: 30px;
}
.closeBtn:hover,
.closeBtnBtn:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
#keyframes modalopen {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" integrity="sha512-5fsy+3xG8N/1PV5MIJz9ZsWpkltijBI48gBzQ/Z2eVATePGHOkMIn+xTDHIfTZFVb9GMpflF2wOWItqxAP2oLQ==" crossorigin="anonymous" />
<link rel="stylesheet" href="style.css">
<title>Note Taker</title>
</head>
<body>
<div class="container">
<h1>Note Taker</h1>
<h5>Add A New Note:</h5>
<form id="note-form">
<div>
<label>Note:</label>
<textarea name="Note" id="note" class="u-full-width"> </textarea>
</div>
<div>
<button type="submit" class="button-primary">Add Note</button>
</div>
</form>
<table>
<tbody class="content"></tbody>
</table>
</div>
<script src="app.js"></script>
</body>
</html>
That happens because when you apply
modal.style.display = "none";
to the modal, you aren't destroying it, you're only hiding it. Additionally, every time you create a modal, and use
const modal = document.querySelector(".modal");
you aren't receiving the new modal you appended to the container, you're receiving the one that it's hidden. That's why the click event doesn't work, because it's being added to the hidden modal. To fix that change,
this:
modal.style.display = "none";
to this:
container.removeChild(modal);
in both EventListeners

TodoList Webpage, better event listener than mouseovert/out? why is my pseudo element ::first-letter not working?

Hello and thanks for stopping by.
I have one main problem with my app.
I think the mouseout and mouseover event listeners are firing like crazy when I put my cursor over the trashcan icon and I don't know why. It gets all glitchy and can't click on it correctly.
Any advice?
https://codepen.io/Dali213/pen/ExjLMdG?editors=0110
const ul = document.querySelector("ul");
//initialisation
const arr = ["learn how to use GitHub.", "learn how to use GitHub.", "learn how to use GitHub."];
for (let i = 0; i < arr.length; i++) {
addToDo(arr[i]);
}
function addToDo(text) {
const li = document.createElement("li");
const p = document.createElement("p");
p.textContent = text;
li.append(p);
li.addEventListener("click", lineThrough);
li.addEventListener("mouseover", addTrashCan);
li.addEventListener("mouseout", removeTrashCan);
ul.append(li);
}
//add rubish icon+delete function
function del() {
const li = this.closest("li");
li.removeEventListener("click", lineThrough);
li.removeEventListener("mouseover", addTrashCan);
li.removeEventListener("mouseout", removeTrashCan);
li.remove();
}
function addTrashCan() {
const trashCan = document.createElement("i");
trashCan.classList.add("far", "fa-trash-alt", "trash-can");
trashCan.addEventListener("click", del);
this.prepend(trashCan);
}
function removeTrashCan() {
const trashCan = this.querySelector("i");
trashCan.removeEventListener("click", del);
trashCan.remove();
}
Second question, at first my pseudo element ::first-letter was working correctly now it isn't.
When I look at the styles applied with the developper tool, it still seems applied though... Why?
Any advice on my code is more than welcome.
Thank you for your time.
You could prepend the trash can in the beginning itself and show/hide based on mouseout or mouseover events instead of creating the element each time:
.hidden {
display: none !important;
}
function addTrashCan() {
this.querySelector('i').classList.remove('hidden')
}
function removeTrashCan() {
this.querySelector('i').classList.add('hidden')
}
function addToDo(text) {
const li = document.createElement("li");
const p = document.createElement("p");
const trashCan = document.createElement("i");
trashCan.classList.add("far", "fa-trash-alt", "trash-can", "hidden");
trashCan.addEventListener("click", del);
li.prepend(trashCan);
p.textContent = text;
li.append(p);
li.addEventListener("click", lineThrough);
li.addEventListener("mouseover", addTrashCan);
li.addEventListener("mouseout", removeTrashCan);
ul.append(li);
}
const ul = document.querySelector("ul");
const input = document.querySelector("input");
//initialisation
const arr = ["learn how to use GitHub.", "learn how to use GitHub.", "learn how to use GitHub."];
for (let i = 0; i < arr.length; i++) {
addToDo(arr[i]);
}
function addToDo(text) {
const li = document.createElement("li");
const p = document.createElement("p");
const trashCan = document.createElement("i");
trashCan.classList.add("far", "fa-trash-alt", "trash-can", 'hidden');
trashCan.addEventListener("click", del);
li.prepend(trashCan);
p.textContent = text;
li.append(p);
li.addEventListener("click", lineThrough);
li.addEventListener("mouseover", addTrashCan);
li.addEventListener("mouseout", removeTrashCan);
ul.append(li);
}
//hide the input
function hideInput() {
input.classList.toggle("hidden");
}
//add task to the list
function enter() {
if (event.keyCode === 13) addToDo(this.value);
}
//line-through on click
function lineThrough() {
this.querySelector("p").classList.toggle("line-through");
}
//add rubish icon+delete function
function del() {
const li = this.closest("li");
li.removeEventListener("click", lineThrough);
li.removeEventListener("mouseover", addTrashCan);
li.removeEventListener("mouseout", removeTrashCan);
li.remove();
}
function addTrashCan() {
/*const trashCan = document.createElement("i");
trashCan.classList.add("far", "fa-trash-alt", "trash-can");
trashCan.addEventListener("click", del);
this.prepend(trashCan);*/
console.log('in');
this.querySelector('i').classList.remove('hidden')
}
function removeTrashCan() {
/*const trashCan = this.querySelector("i");
trashCan.removeEventListener("click", del);
trashCan.remove();*/
console.log('out');
this.querySelector('i').classList.add('hidden')
}
//listeners
document.querySelector(".display").onclick = hideInput;
input.onkeyup = enter;
* {
padding: 0px;
margin: 0px;
}
body {
background: linear-gradient(90deg, #18b7e4, #e8e9be);
}
.container {
background-color: aliceblue;
min-width: 270px;
max-width: 270px;
margin: 80px auto 0px;
}
.head {
padding: 5px 10px;
display: flex;
justify-content: space-between;
background-color: #2072b5;
color: #ffffff;
}
.display,
i {
cursor: pointer;
}
input {
border: 2px solid #2072b5;
width: 246px;
padding: 5px 10px;
}
.hidden {
display: none !important;
}
ul {
list-style: none;
}
p {
display: inline;
padding: 2px 5px;
}
p::first-letter {
text-transform: capitalize;
}
li:nth-of-type(odd) {
background-color: #f7f5f7;
}
li:nth-of-type(even) {
background-color: #ffffff;
}
.line-through {
text-decoration: line-through;
opacity: 0.7;
}
.trash-can {
background-color: red;
color: #ffffff;
padding: 2px 5px;
}
li {
display: flex;
}
<!DOCTYPE html>
<html>
<head>
<title>to-do list</title>
<link rel="stylesheet" href="main.css" />
<script src="https://kit.fontawesome.com/fe178342de.js" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="head">
<h1>TO-DO LIST</h1>
<h1 class="display">+</h1>
</div>
<input type="text" placeholder="Add New Todo" />
<ul></ul>
</div>
<script src="main.js"></script>
</body>
</html>
Edit:
To fix the ::first-letter pseudo element, issue you could add the following css:
li {
display: flex;
}

localStorage is not working in JavaScript

I'm trying to make a Single Page Application with pure JavaScript (no additional frameworks or libraries). The problem is that the values I add to the TODO list are not storing in the localStorage (and are not showing).
I would appreciate any help with that task.
How can I simplify the code? (without using any additional libraries and frameworks (ex.jquery etc.))
Here is my code:
let inputTask = document.getElementById('toDoEl');
let editTask = document.getElementById('editTask');
let checkTask = document.getElementById('list');
let emptyList = document.getElementById('emptyList');
let items = [];
let id = [];
let labelToEdit = null;
const empty = 0;
let pages = ['index', 'add', 'modify'];
load();
function load() {
items = loadFromLocalStorage();
id = getNextId();
items.forEach(item => renderItem(item));
}
function show(shown) {
location.href = '#' + shown;
pages.forEach(function(page) {
document.getElementById(page).style.display = 'none';
});
document.getElementById(shown).style.display = 'block';
return false;
}
function getNextId() {
for (let i = 0; i<items.length; i++) {
let item = items[i];
if (item.id > id) {
id = item.id;
}
}
id++;
return id;
}
function loadFromLocalStorage() {
let localStorageItems = localStorage.getItem('items');
if (localStorageItems === null) {
return [];
}
return JSON.parse(localStorageItems);
}
function saveToLocalStorage() {
localStorage.setItem('items', JSON.stringify(items));
}
function setChecked(checkbox, isDone) {
if (isDone) {
checkbox.classList.add('checked');
checkbox.src = 'https://image.ibb.co/b1WeN9/done_s.png';
let newPosition = checkTask.childElementCount - 1;
let listItem = checkbox.parentNode;
listItem.classList.add('checked');
checkTask.removeChild(listItem);
checkTask.appendChild(listItem);
} else {
checkbox.classList.remove('checked');
checkbox.src = 'https://image.ibb.co/nqRqUp/todo_s.png';
let listItem = checkbox.parentNode;
listItem.classList.remove('checked');
}
}
function renderItem(item) {
let listItem = document.getElementById('item_template').cloneNode(true);
listItem.style.display = 'block';
listItem.setAttribute('data-id', item.id);
let label = listItem.querySelector('label');
label.innerText = item.description;
let checkbox = listItem.querySelector('input');
checkTask.appendChild(listItem);
setChecked(checkbox, item.isDone);
emptyList.style.display = 'none';
return listItem;
}
function createNewElement(task, isDone) {
let item = { isDone, id: id++, description: task };
items.push(item);
saveToLocalStorage();
renderItem(item);
}
function addTask() {
if (inputTask.value) {
createNewElement(inputTask.value, false);
inputTask.value = '';
show('index');
}
}
function modifyTask() {
if (editTask.value) {
let item = findItem(labelToEdit);
item.description = editTask.value;
labelToEdit.innerText = editTask.value;
saveToLocalStorage();
show('index');
}
}
function findItem(child) {
let listItem = child.parentNode;
let id = listItem.getAttribute('data-id');
id = parseInt(id);
let item = items.find(item => item.id === id);
return item;
}
// Chanhe img to checked
function modifyItem(label) {
labelToEdit = label;
editTask.value = label.innerText;
show('modify');
editTask.focus();
editTask.select();
}
function checkItem(checkbox) {
let item = findItem(checkbox);
if (item === null) {
return;
}
item.isDone = !item.isDone;
saveToLocalStorage();
setChecked(checkbox, item.isDone);
}
function deleteItem(input) {
let listItem = input.parentNode;
let id = listItem.getAttribute('data-id');
id= parseInt(id);
for (let i in items) {
if (items[i].id === id) {
items.splice(i, 1);
break;
}
}
if (items.length === empty) {
emptyList.style.display = 'block';
}
saveToLocalStorage();
listItem.parentNode.removeChild(listItem);
}
* {
box-sizing: border-box;
}
body {
font-family: sans-serif;
}
h2, li, #notification {
text-align: center;
}
h2 {
font-weight: normal;
margin: 0 auto;
padding-top: 20px;
padding-bottom: 20px;
}
#root {
width: 400px;
height: 550px;
margin: 0 auto;
position: relative;
}
#root>ul {
display: block;
}
#addButton {
display: block;
margin: 0 auto;
}
.checkbox, .delete {
height: 24px;
bottom: 0;
}
.checkbox {
float: left;
}
.delete {
float: right;
}
ul {
margin: 20px 30px 0 30px;
padding-top: 20px;
padding-left: 20px;
text-align: center;
}
#toDoEl {
width: 50%;
}
li {
width: 100%;
list-style: none;
box-sizing: border-box;
display: flex;
justify-content: space-between;
align-items: center;
margin: 15px auto;
}
label {
margin: 0 auto;
text-align: justify;
text-justify: inter-word;
}
label:hover {
cursor: auto;
}
li.checked {
background-color: gray;
}
span.button {
cursor: pointer;
}
#add, #modify {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Homework 12 - Simple TODO List</title>
<link rel="stylesheet" href="./assets/styles.css">
</head>
<body>
<div id="root">
<!--Main page-->
<div id="index">
<h2>Simple TODO Application</h2>
<button class="button" id="addButton" onclick="show('add')">Add New Task</button>
<p id="emptyList">TODO is empty</p>
<ul id="list">
<li id="item_template" style="display: none">
<input class="checkbox" type="image" alt="checkbox" src="https://image.ibb.co/nqRqUp/todo_s.png" onclick="checkItem(this)">
<label onclick="modifyItem(this)"></label>
<input id="delete" class="delete" type="image" alt="remove" src="https://image.ibb.co/dpmqUp/remove_s.jpg" onclick="deleteItem(this)">
</li>
</ul>
</div>
<!--Add page-->
<div id="add">
<h2>Add Task</h2>
<input type="text" id="toDoEl">
<button class="button cancel" onclick="show('index')">Cancel</button>
<button class="button save" onclick="addTask()">Save changes</button>
</div>
<!--Modify page-->
<div id="modify">
<h2>Modify item</h2>
<input type="text" id="editTask">
<button class="button cancel" onclick="show('index')">Cancel</button>
<button class="button save" onclick="modifyTask()">Save changes</button>
</div>
</div>
<script src="./src/app.js"></script>
</body>
</html>
Your code does appear to work. If you console.log(JSON.parse(localStorageItems)) right above line 49 in the loadFromLocalStorage function, it shows as expected in the console. Also, upon refreshing the items persist.
If what you mean is that you're checking localStorage and you don't see the items, it might be that you're looking at the preview version of localStorage. (I'm assuming you're using Chrome.) Hover over the top of the empty section and pull down, this should reveal the values stored. If you click on one, it should show in the preview section. I think this was a Chrome dev tools UI change recently implemented.
I checked your code in Codepen and it works.

deleting an element onClick from an array of objects

i am doing the library project from "odin project" website and i am having trouble completing it. my idea is to access the cards particular index in the "library" array of objects, but i am having trouble doing so. my idea is to have a function that creates some type of id from its place in the array ( such as its index ) and use that as access for my delete button. any suggestions? i appreciate your time here is my codepen link
//constructor to add a book to
function Book(title, author, pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
//array of books
const library = [];
//hides and unhides forms
const hide = () => {
var form = document.querySelector("#hide");
if (form.style.display === "none") {
form.style.cssText =
"display: block; display: flex; justify-content: center; margin-bottom: 150px";
} else {
form.style.display = "none";
}
};
//creates form, takes input,creates card, resets and runs hide function when done
const addBookCard = () => {
const bookName = document.querySelector('input[name="bookName"]').value;
const authorName = document.querySelector('input[name="authorName"]').value;
const numPages = document.querySelector('input[name="numPages"]').value;
library.push(new Book(bookName, authorName, numPages));
//just stating variables used within my function
const container = document.querySelector(".flex-row");
const createCard = document.createElement("div");
const divTitle = document.createElement("p");
const divAuthor = document.createElement("p");
const divPages = document.createElement("p");
const deleteBtn = document.createElement("button");
//using a class from my css file
createCard.classList.add("card");
createCard.setAttribute("id","id_num")
deleteBtn.setAttribute("onclick", "remove()")
deleteBtn.setAttribute('id','delBtn')
//geting all info from library
divTitle.textContent = "Title: " + bookName
divAuthor.textContent = "Author: " + authorName
divPages.textContent = "Number of Pages: " + numPages
deleteBtn.textContent = "Delete This Book";
//adding it all to my html
container.appendChild(createCard);
createCard.appendChild(divTitle);
createCard.appendChild(divAuthor);
createCard.appendChild(divPages);
createCard.appendChild(deleteBtn);
document.getElementById("formReset").reset();
hide()
return false
};
var btn = document.querySelector('#newCard');
btn.onclick = addBookCard;
You can change library declaration from const to let.
Then you can push books together with their corresponding deleteBtn, that way you will be able to easily remove an entry that corresponds to the clicked deleteBtn
library.push([new Book(bookName, authorName, numPages), deleteBtn]);
And then you can add event listener on deleteBtn like this
deleteBtn.addEventListener('click', event => {
event.target.parentNode.remove();
library = library.filter(v => v[1] !== event.target);
});
Where the first line removes the element from the DOM, and the second line creates new library array without the removed entry.
function Book(title, author, pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
//array of books
let library = [];
//hides and unhides forms
const hide = () => {
var form = document.querySelector("#hide");
if (form.style.display === "none") {
form.style.cssText =
"display: block; display: flex; justify-content: center; margin-bottom: 150px";
} else {
form.style.display = "none";
}
};
//creates form, takes input,creates card, resets and runs hide function when done
const addBookCard = () => {
const bookName = document.querySelector('input[name="bookName"]').value;
const authorName = document.querySelector('input[name="authorName"]').value;
const numPages = document.querySelector('input[name="numPages"]').value;
//just stating variables used within my function
const container = document.querySelector(".flex-row");
const createCard = document.createElement("div");
const divTitle = document.createElement("p");
const divAuthor = document.createElement("p");
const divPages = document.createElement("p");
const deleteBtn = document.createElement("button");
library.push([new Book(bookName, authorName, numPages), deleteBtn]);
deleteBtn.addEventListener('click', event => {
event.target.parentNode.remove();
library = library.filter(v => v[1] !== event.target);
});
//using a class from my css file
createCard.classList.add("card");
createCard.setAttribute("id","id_num")
deleteBtn.setAttribute('id','delBtn')
//geting all info from library
divTitle.textContent = "Title: " + bookName
divAuthor.textContent = "Author: " + authorName
divPages.textContent = "Number of Pages: " + numPages
deleteBtn.textContent = "Delete This Book";
//adding it all to my html
container.appendChild(createCard);
createCard.appendChild(divTitle);
createCard.appendChild(divAuthor);
createCard.appendChild(divPages);
createCard.appendChild(deleteBtn);
document.getElementById("formReset").reset();
hide()
return false
};
var btn = document.querySelector('#newCard');
btn.onclick = addBookCard;
function hello (){
for (var i = 0; i < library.length ;i++) {
console.log(library[i]);
}
}
body {
margin: 0 auto;
width: 960px;
//background: cyan;
}
.flex-row {
display: flex;
flex-wrap: wrap;
}
.flex-column {
display: flex;
flex-direction: column;
}
.flex-row-form {
display: flex;
justify-content: center;
}
.flex-column-form {
display: flex;
flex-direction: column;
background: purple;
width: 45%;
padding: 20px;
border-radius: 5px;
border: 2px solid black;
color: white;
font-weight: 300;
font-size: 24px;
}
.card {
width: 33.33%;
text-align: center;
height: 200px;
border: 1px solid black;
padding: 20px;
margin: 10px;
border-radius: 10px;
}
.text {
padding-bottom: 20px;
font-weight: 300;
font-size: 20px;
}
p {
font-size: 20px;
font-weight: 400;
}
#newBook {
margin: 30px;
padding: 10px 20px;
cursor: pointer;
font-size: 16px;
color: #dff;
border-radius: 5px;
background: black;
}
#delBtn{
padding:10px;
border-radius:5px;
background:red;
color:white;
font-size:14px;
cursor: pointer;
}
<div id="display"></div>
<button id="newBook" onclick="hide()">New Book</button>
<div class="flex-row-form" id="hide" style= "display:none">
<form class="flex-column-form" id="formReset">
Book Name: <input type="text" name="bookName" value="Book Name" id="title"><br>
Author Name: <input type="text" name="authorName" value="Author Name " id="author"<br>
Number of Pages: <input type="text" name="numPages" value="# of Pages" id="pages" ><br>
<button id="newCard"> Add Book to Library</button>
</form>
</div>
<div class="flex-row">
</div>
And I have removed this line
deleteBtn.setAttribute("onclick", "remove()")
you don't need it anymore since I have added event listener for that button, and it was throwing an error because you didn't define remove function in your code.

Hide popup window if click out his area [duplicate]

I want to make a popup that should appear once a button is clicked and disappear once the user clicks outside of the box.
I'm not sure how to make the div disappear when I click outside of it.
var popbox = document.getElementById("popbox");
document.getElementById("linkbox").onclick = function () {
popbox.style.display = "block";
};
???.onclick = function () {
popbox.style.display = "none";
};
Here is the second version which has a transparent overlay as asked by the asker in the comments...
window.onload = function(){
var popup = document.getElementById('popup');
var overlay = document.getElementById('backgroundOverlay');
var openButton = document.getElementById('openOverlay');
document.onclick = function(e){
if(e.target.id == 'backgroundOverlay'){
popup.style.display = 'none';
overlay.style.display = 'none';
}
if(e.target === openButton){
popup.style.display = 'block';
overlay.style.display = 'block';
}
};
};
#backgroundOverlay{
background-color:transparent;
position:fixed;
top:0;
left:0;
right:0;
bottom:0;
display:block;
}
#popup{
background-color:#fff;
border:1px solid #000;
width:80vw;
height:80vh;
position:absolute;
margin-left:10vw;
margin-right:10vw;
margin-top:10vh;
margin-bottom:10vh;
z-index:500;
}
<div id="popup">This is some text.<input type="button" id="theButton" value="This is a button"></div>
<div id="backgroundOverlay"></div>
<input type="button" id="openOverlay" value="open popup">
Here is the first version...
Here is some code. If there is anything else to add, please let me know :)
The event (e) object gives access to information about the event. e.target gives you the element that triggered the event.
window.onload = function(){
var divToHide = document.getElementById('divToHide');
document.onclick = function(e){
if(e.target.id !== 'divToHide'){
//element clicked wasn't the div; hide the div
divToHide.style.display = 'none';
}
};
};
<div id="divToHide">Click outside of this div to hide it.</div>
Here, the idea is to detect click events on the page and set the container’s display to none only when the target of the click isn’t one of the div descendants.
HTML
<div id="container">
<label>Enter your name:</label>
<input type="text">
<button id="submit">Submit</button>
</div>
JS
document.addEventListener('mouseup', function(e) {
var container = document.getElementById('container');
if (!container.contains(e.target)) {
container.style.display = 'none';
}
});
This is code I use to close my side bar when click outside
function openNav() {
document.getElementById("mySidebar").style.width = "100px";
document.getElementById("curtain_menu").style.marginLeft = "100px";
}
function closeNav() {
document.getElementById("mySidebar").style.width = "0";
document.getElementById("curtain_menu").style.marginLeft = "0";
}
document.onclick = function (e) {
if (e.target.id !== 'mySidebar' && e.target.id !== 'btn_frontpage_menu') {
if (e.target.offsetParent && e.target.offsetParent.id !== 'mySidebar')
closeNav()
}
}
.sidebar {
font-family: sans-serif;
height: 50%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
opacity: 0.9;
}
.sidebar a,
.dropdown-btn {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 1vw !important;
color: rgb(195, 195, 195);
display: block;
background: none;
width: 100%;
text-align: left;
cursor: pointer;
outline: none;
transition: 0.3s;
border: none;
}
.dropdown-container a {
color: rgb(174, 174, 174) !important;
}
.sidebar a:hover,
.dropdown-btn:hover,
.dropdown-container a:hover {
color: green !important;
/* background-color: #5c5c5c; */
}
.sidebar .closebtn {
position: absolute;
top: 12px;
font-size: 36px !important;
margin-right: 5px;
text-align: right;
right: 20px;
}
.openbtn {
font-size: 20px !important;
cursor: pointer;
background-color: transparent;
color: black;
padding: 6px 15px;
border: none;
float: left;
}
#main {
position :absolute;
width: 100%;
height: 100%;
left: 100px
}
<div id="mySidebar" class="sidebar" style="width: 100px;">
<a href="javascript:void(0)" class="closebtn"
onclick="closeNav()">×</a>
Home
<div class="dropdown-container">
Job Management
Request
Pending
</div>
</div>
<div id="curtain_menu">
<button id="btn_frontpage_menu" class="openbtn" onclick="openNav()">☰</button>
<div id="datetime"></div>
</div>
<div id="main"> Outside of 'Side Bar' is here
</div>
Here is my Solution.
yourFunc=e=>{
var popbox = document.getElementById("popbox");
if(e.target.id !=="popbox"){
popbox.style.display = "none";
}else{
popbox.style.display = "block";
}
}
document.addEventListener("click",yourFunc)
hope this will work for you
<script>
// Get the element
var modal = document.getElementById('modal');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
This code is tested and it's working nicely, thank you.
Could be done with onblur event.
// required for focus
divEl.setAttribute('tabindex', '1');
divEl.onblur = event => {
// hide only if blur occurred outside divEl, ignore its children
if (!event.currentTarget.contains(event.relatedTarget)) {
hide();
}
// re-focus, if a child took it
divEl.focus();
};
divEl.focus();
P.S. For IE11 a small hack event.relatedTarget = event.relatedTarget || document.activeElement; could be required.
<div class='icon alk-icon-close'>hidden hire</div>
document.addEventListener('click', function(e) {
var target = e.target.classList.value
if (target == 'icon alk-icon-close') ) {
hidden hire
}
});
plug this in
(function(){
// click outside of element to hide it
let hels = [];
window.hidable = (el, excepter, hider) => {
// hider takes el as the only arg
hels.push([el, excepter, hider]);
return el;
}
window.addEventListener('click', e=>{
for(let i = 0; i < hels.length; i++){
let el = hels[i][0];
let excepter = hels[i][1];
let hider = hels[i][2];
if(!el.contains(e.target) && excepter !== e.target){
hider(el);
}
}
});
})()
unit test
/* excepter is the element to trigger panel show */
// example implementation
window.hidable(panel_el, show_panel_button, el=>el.remove());
// other hiders can be:
el=>el.style.display = 'none';
// depends on your show implementation
el.onmouseleave = function(){
document.body.onclick = function(){
el.style.display = 'none';
document.body.onclick = null;
}
}
Okay, here's a jQuery based solution based on any div clicked within the DOM.
$('div').on('click', function(e){
var parents = $(e.currentTarget).parents();
for (var i = 0; i < parents.length; i++) {
if (parents[i].id === 'divToHide' || e.currentTarget.id === 'divToHide') {
// you are in the popup
};
}
e.stopPropagation();
});
This looks at your current element, as well as any of the parents, and checks if the id matches up. If divToHide is in the parents() list, then you keep the popup open.
*NOTE: This requires wrapping your content within a wrapper div or something similar.

Categories