Created
April 7, 2021 18:40
-
-
Save luisvinicius09/09b4c607d9bdac850f03f977fdcc0576 to your computer and use it in GitHub Desktop.
This is a snippet for creating 'projects' and storing it in on localStorage.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const projectBtn = document.querySelector('#project-btn'); | |
const projectName = document.querySelector('#new-project'); | |
window.addEventListener('load', () => { | |
if(JSON.parse(localStorage.getItem('projects')) === null) { | |
localStorage.setItem('projects', JSON.stringify(new Array)); | |
} | |
displayProjects(); | |
}) | |
const createProject = (name) => { | |
return { name }; | |
} | |
const updatedProjects = () => { | |
const temp = JSON.parse(localStorage.getItem('projects')); | |
return temp; | |
} | |
const updateProjects = (arr) => { | |
localStorage.setItem('projects', JSON.stringify(arr)); | |
} | |
const addNewProject = (name) => { | |
const item = createProject(name); | |
const temp = updatedProjects(); | |
temp.push(item); | |
updateProjects(temp); | |
projectName.value = ""; | |
} | |
const displayProjects = () => { | |
const temp = updatedProjects(); | |
const p = temp.map(project => ( | |
`<p>${project.name}</p>` | |
)).join('\n'); | |
document.querySelector('#projects-container').innerHTML = p; | |
} | |
const validateInput = (id) => { | |
if(id.value === null || id.value === "") { | |
alert('Please fill the required fields'); | |
return true; | |
} | |
} | |
projectBtn.addEventListener('click', () => { | |
if (!validateInput(projectName)) { | |
addNewProject(projectName.value); | |
displayProjects() | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment