Use LocalStorage With JavaScript and a task manager sample project

Local storage is a client-side data storage feature. It is completely JavaScript-based, so no need for server end programming required.
Generally, we are using two types of storage in client end programming.

1. LocalStorage: LocalStorage data will be consistent even after a refresh or close the browser window.
2. Session or Cookies storage: Session or cookies-based storage has a time limit. Generally, cookies data destroy after close the browser window.

Highlight key features of LocalStorage.

  • Full JavaScript-based, so no need for any server programming.
  • Hold value after close the browser window.
  • Can store array and object values as well, but need to convert JSON string format. using a method called JSON.stringify() and JSON.parse()
  • LocalStorage provides almost 5MB of data storage.

Four methods are related to LocalStorage

1. getItem() => Get a key value from localStorage Object
2. setItem() => Add Key and value to localStorage
3. removeItem() => Remove paticular item by key

Now let start with an example. This is a simple task management application, an HTML form submit the task detail and we will store them to localStorage and render it on the HTML page.

HTML Code

<div class="wrapper">
			<h1 class="page-heading">My Task Board</h1>
			<div class="task-form">
				<form method="post" id="taskGenerate">
					<div class="form-field">
						<label for="taskName">Task Name</label>
						<input type="text" name="taskName" id="taskName" required="true">
					</div>
					<div class="form-field">
						<label for="taskName">Task Time</label>
						<input type="text" name="taskTime" id="taskTime" required="true">
					</div>
					<div class="form-field">
						<label for="taskDescription">Task Description</label>
						<textarea name="taskDescription" id="taskDescription" required="true"></textarea>
					</div>
					<div class="form-field">
						<button type="submit">Submit</button>
					</div>
				</form>
			</div>
			<div class="task-list-wrapper">
				<ul id="taskList"class="task-list-items">
				</ul>
			</div>
		</div>

CSS Code

body{
	margin:0px;
	padding:0px;
	font-size:100%;
	font-family:sans-serif;
}

.wrapper{
	max-width:768px;
	width:100%;
	margin:0px auto;
	padding:0px 10px;
}

.wrapper .page-heading{
	text-align:center;
	margin-top:20px;
}

.task-form{
	max-width:500px;
	display:block;
	border:1px solid;
	border-radius:5px;
	padding:10px;
	margin: 0 auto;
}

.task-form .form-field{
	width:100%;
	margin-bottom:15px;
}

.form-field label{
	width:100%;
	clear:both;
	display:block;
	font-size:16px;
}
.form-field input[type=text], .form-field textarea{
	width:100%;
	clear:both;
	display:block;
	font-size:16px;
	padding:5px;
	border-radius:5px;
}

.form-field button{
	max-width:100px;
	display:block;
	width:100%;
	padding:10px;
	background-color:#15af44e6;
	color:#FFFFFF;
	font-size:20px;
	text-transform: uppercase;
	text-transform: uppercase;
    border: 1px solid;
    border-radius: 5px;
}

.task-list-wrapper{
	display:block;
	margin-top:20px;
}

.task-list-items{
	list-style:none;
	margin:0px;
	padding:0px;
	display: flex;
    /* flex-direction: row; */
    flex-wrap: wrap;
    width: 100%;
}

.task-list-items li {
    list-style: none;
    display: block;
    max-width: 222px;
    margin-right: 12px;
    /* flex-flow: column; */
    margin-bottom: 20px;
    /* flex-grow: 2; */
    padding: 10px;
    width: 100%;
    border: 1px solid;
    border-radius: 5px;
	max-height:200px;
	overflow-y:auto;
    /* width: calc(100% / 4); */
    /* flex: auto; */
    /* justify-content: space-between;
}

JavaScript Code

// render localStorage task list
document.addEventListener("DOMContentLoaded", function(){
	renderListData();
	
});

document.addEventListener('click',function(e){
	
    if(e.target && e.target.className == 'removeTask'){
		//console.log(e.target.className);
        let removeTaskBtn = e.target // document.querySelectorAll('a.removeTask');
		//console.log(removeTaskBtn);
		if(removeTaskBtn){
			event.preventDefault();
			let removeIndex = event.target.getAttribute('data-key');
			//console.log(removeIndex);
			let tasksList = JSON.parse(localStorage.getItem('tasks_mgmt'));
			let removeTaskList = tasksList.splice(removeIndex,1);
			//console.log(removeIndex, removeTaskList, tasksList);
			localStorage.setItem('tasks_mgmt', JSON.stringify(tasksList));
			renderListData();
		}
    }
 });


// submit form and store task
document.querySelector('form#taskGenerate').addEventListener('submit', function(event){

	event.preventDefault();
	let taskName = document.querySelector('#taskName');
	let taskTime = document.querySelector('#taskTime');
	let taskDescription = document.querySelector('#taskDescription');
	let taskStatus = document.querySelector('#taskDescription');
	
	letNewTask = { 'taskName' : taskName.value, 'taskTime' : taskTime.value, 'taskDescription' : taskDescription.value };
	//console.log(taskName,taskTime,taskDescription);
	let tasksList;
	
	if(localStorage.getItem('tasks_mgmt') == null){
		tasksList = [];
	} else {
		tasksList = JSON.parse(localStorage.getItem('tasks_mgmt'));
	}
	
	tasksList.push(letNewTask);
	localStorage.setItem('tasks_mgmt', JSON.stringify(tasksList));
	
	taskName.value = '';
	taskTime.value = '';
	taskDescription.value = '';
	renderListData();
	
});

function renderListData(){
	// Handler when the DOM is fully loaded
	const tasks = JSON.parse(localStorage.getItem('tasks_mgmt'));
	//console.log(tasks);
	let taskList = '';
	const taskUlEl = document.querySelector('#taskList');
	taskUlEl.innerHTML = '';
	tasks.forEach(function(task, index){
		taskUlEl.innerHTML += '<li data-key="'+ index +'"><h2>'+task.taskName+'</h2> <p><strong>Time: </strong>'+ task.taskTime +'</p> <p>'+ task.taskDescription +'</p> <a class="removeTask" href="#" data-key="'+ index +'">Remove</a> </li>';
	});
}

GitHub repository url