document.addEventListener('DOMContentLoaded', function(){
modalFunction();
saveFunction();
});
//creating user's input to get the relevant data..
function modalFunction(){
var modal = document.querySelector('.modal'),
btn = document.getElementById('add'),
closeBtn = document.getElementById('cancel'),
saveBtn = document.getElementById('save');
//for opening modal..
btn.addEventListener('click', function(){
modal.classList.add('active');
});
//for closing modal using cancel button and esc keypress..
closeBtn.addEventListener('click', function(){
modal.classList.remove('active');
});
modal.addEventListener('keydown', function(event){
if(event.key === 'Esc'){
modal.classList.remove('active');
}
});
//adding event listners to run the saveitem() function..
saveBtn.addEventListener('click', function(){
saveItem();
});
modal.addEventListener('keydown', function(event){
if(event.key === 'Enter'){
event.preventDefault();
saveItem();
}
});
// Initializing the local storage array once
if (!localStorage.getItem('list')) {
localStorage.setItem('list', JSON.stringify([]));
}
//defining saveitem() function here...
function saveItem(){
var heading = document.getElementById('heading'),
content = document.getElementById('content');
if (heading.value !== '' && content.value !== '') {
//closing modal on successful submission..
modal.classList.remove('active');
//creating local storage...
let data = JSON.parse(localStorage.getItem('list') || []);
data.push({h:heading.value, p:content.value});
localStorage.setItem('list', JSON.stringify(data));
//refreshing values after successful submission..
heading.value = '';
content.value = '';
}else{
alert('Please fill out these fields!')
}
}
}
//printing the user's data..
function saveFunction(){
var screen = document.querySelector('main div')
storedItems = JSON.parse(localStorage.getItem('list'));
var screen = document.querySelector('main div');
screen.innerHTML = '';
// Display static heading
var headingElement = document.createElement('h1');
headingElement.innerText = 'To Do List';
screen.appendChild(headingElement);
if (storedItems && storedItems.length > 0) {
storedItems.forEach(item => {
let div = document.createElement('div'),
h = document.createElement('h3'),
p = document.createElement('p');
h.innerText = item.h;
p.innerText = item.p;
div.classList.add('screen');
div.appendChild(h);
div.appendChild(p);
screen.appendChild(div);
});
}else{
let msg = document.createElement('p');
msg.innerText = 'Nothing to See! click add new button on the bottom right corner of this page to create a new list!'
screen.appendChild(msg);
}
}
Top comments (2)
Your question must be a bit clear
Actually I want to show to added content right after it is added, but this code requires a browser refresh to show to newly added content, if you want then I will give you html and css file accordingly