Leveraging HTML5's local storage functionality to save and manage a collection of list elements within `<ul>`

I need help with saving a to-do list in HTML so that it persists even after refreshing the browser. Can anyone assist me?

html

<!DOCTYPE html>
<html>

    <head>
        <title>My To-Do List</title>
        <link rel="stylesheet" href="css/styles.css" />
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="css/font-awesome-animation.min.css">
        <link href='https://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>
        <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
        <link rel="icon" href="/favicon.ico" type="image/x-icon">
    </head>

    <body>
        <div id="page">
            <header>
                <img src="images/checklist.png" alt="some_text">
            </header>
             <h2>MY TO-DO LIST</h2>

            <ul id="sortable"></ul>
            <form id="newItemForm">
                <input type="text" id="itemDescription" placeholder="Add Description" maxlength="40" />
                <input type="submit" id="add" value="add" />
                <div id="double">Drag and drop to rearrange items
                    <br />Click on an item to remove it</div>
            </form>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script src="js/main.js"></script>
        <script src="js/sort.js"></script>
        <script src="jquery-ui/jquery-ui.js"></script>
    </body>

</html>

JavaScript/jQuery

$(function () {

    var $list;
    var $newItemForm;
    var $newItemButton;
    var item = '';
    $list = $('ul');
    $newItemForm = $('#newItemForm');
    $newItemButton = $('#newItemButton');

    // ADDING A NEW LIST ITEM
    $newItemForm.on('submit', function (e) {
        e.preventDefault();
        var text = $('input:text').val();
        $list.append('<li>' + text + '</li>');
        $('input:text').val('');
    });

    $list.on('click', 'li', function () {
        var $this = $(this);
        var complete = $this.hasClass('complete');

        if (complete === true) {
            $this.animate({}, 500, 'swing', function () {
                $this.remove();
            });
        } else {
            item = $this.text();
            $this.remove();
        }
    });

});

localStorage.setItem($list);

//add animations when you learn how to...

Answer №1

To ensure proper functionality, it is important to store the data in an object rather than just keeping it in the DOM. Whenever a new todo is added or an existing one is edited, make sure to save that information to the localstorage. Remember, storing DOM nodes directly to localStorage will not work as it only accepts string values.

Here's a revised version of your code:

// Define localStorage key
var lsKey = 'TODO_LIST';

// Initialize data storage object
var todoList = {};

function getSavedData () {
    var fromLs = localStorage.getItem( lsKey );

    if ( !! fromLs ) {
        todoList = JSON.parse( fromLs );
    } else {
        todoList = {};
        localStorage.setItem( lsKey, JSON.stringify(todoList) );
    };
};

function saveData () {
    var stringify = JSON.stringify( todoList );
    localStorage.setItem( lsKey, stringify );
};

$newItemForm.on('submit', function(e) {
    e.preventDefault();

    var text = $('input:text').val().trim(),
        uuid = Date.now();

    // Use input[type:checkbox] to determine completion status
    if ( !! text ) {
        todoList[uuid] = text;
        $list.append('<li><input type="checkbox" id=' + uuid + ' /> ' + text + '</li>');
        $( 'input:text' ).val( '' );
    };
});

$list.on('change', 'li input', function() {
    var uuid = $(this).attr( 'id' ),
        $li  = $(this).parent();

    if ( $(this).prop('checked') ) {
        todoList[uuid] = undefined;
        delete todoList[uuid];

        saveData();

        $li.fadeOut("slow", function() {
            $this.remove();
        });
    };
});

Best of luck and enjoy coding!

Answer №2

To ensure proper data storage, remember two key steps: first, save only your data without any HTML content. Second, provide a unique name for your item in localStorage as this is a key/value storage system requiring a specific identification key. Additionally, since localStorage stores data as string values, make sure to use JSON.stringify() before saving your data. Your code should resemble the following format: localStorage.setItem("yourKeyName", JSON.stringify(yourDataObj)). When retrieving your data, utilize JSON.parse(localStorage.getItem("yourKeyName")) to convert it back into a JSON object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Some mobile web browsers are experiencing difficulties when trying to load a background video coded in html5

There is a full background HTML5 video set to autoplay on my website. However, there seems to be an issue with some iOS mobile devices using Safari as the video fails to load properly at times. The error message displayed is: https://i.stack.imgur.com/D4X ...

Double-checked in p:commandButton, encountering a race condition with oncomplete

When I execute the server action using p:commandButton, I then refresh the form to display hidden fields and show a dialog. Attempting to refresh only the panels with hidden buttons yields the same result: After I call dialog.show(), a second refresh is t ...

Tips for generating multiple URL destinations within a single hyperlink

I am looking to create a unique feature in HTML where multiple tabs can be opened with different URLs using one link. While I know how to open one link in a new tab, I am unsure of how to simultaneously add another URL that will open up in a separate tab ...

Tips for employing numerous if-else conditions utilizing the ternary operator in jsonpath-plus?

JSON { "customer":{ "address":{ "stateRegion":"", "stateRegionCode":"" } } } Code "address.state_code": "$.customer.address.[stateRegion ? state ...

When the PHP response is received by AJAX, an error occurs due to a failed JSON parsing request

Every time I try to run my small JavaScript code with an AJAX call to PHP, it keeps coming back with a JSON parser error. In the PHP code, I can see that the JSON is populated with an array like this: json encode: {"Year":"2012","Make":"Ford","Model":"Tau ...

There is a runtime error in Microsoft JScript, as the object does not support the property or method '__defineGetter__'

Upon opening my project in IE9, I encountered the error message: "Microsoft JScript runtime error: Object doesn't support property or method 'defineGetter'." Can anyone provide guidance on how to resolve this issue? ...

Contrasting outcomes when tackling a problem in node.js versus python

After tackling a challenging leetCode problem, I successfully came up with the following solution: Given d dice, each with f faces numbered from 1 to f, determine the number of possible ways (modulo 10^9 + 7) to roll the dice so the sum of the face up nu ...

Utilizing Angular 6 and JavaScript to invoke two functions within an (ngClick) event in both the Component and JavaScript

I have a requirement to execute two functions in my click event, one for my component and the other for a custom JavaScript function. Here is the code snippet: Angular click event: <button type="button" class="btn btn-primary" (click)="Plans(); " [att ...

I am utilizing the ternary operator within the map function to dynamically adjust the column width of a material table

Looking to adjust column widths based on the IDs received from the map function. Check out the code snippet: <TableRow> { tableData.header.map(header => { header.i ...

Ensure accurate detection of invalid values for SVG Elements in React using jest testing framework

When testing my react app, I am attempting to capture any errors that are thrown or logged to the console. If a regular HTML element such as <p> contains invalid attributes like <p color={false}></p>, react will display an error via cons ...

If PHP does not return data in a JSON encoded format, Ajax will not function properly

I have a PHP script that returns an array if an error occurs, otherwise it returns a <DIV> if(!empty($error)) { $true = true; $res = array('info' => '$error', 'error' => '$true'); echo json_enc ...

Issue: The `libsass` component could not be located

When attempting to run an Express app using node-sass-middleware on Ubuntu, I encountered this error: 0 info it worked if it ends with ok 1 verbose cli [ '/home/mohamed/.nvm/versions/node/v0.12.7/bin/node', 1 verbose cli '/home/mohamed/.n ...

Depending on external software packages

Can you explain the potential risks associated with using third-party packages and npm in a broader sense? If I were to install a third-party package like semantic-ui-react using npm, is there a possibility that I may not be able to use it on my website i ...

Best practices for handling errors beyond network problems when using the fetch() function

I am facing a situation where the route of my fetch() call can result in two different responses, each requiring a different action. However, I have noticed that the catch() method only handles network errors as far as I know. Currently, my code looks lik ...

In what way can you reach an unfamiliar form within a controller?

I am working with multiple dynamically generated forms, each associated with a different model. In my controller, I need to iterate through all the errors within the forms. I assign form names based on the models. <form name="{{myForm}}" novalidate> ...

What is the proper way to integrate three.js (a third-party library) into the view controller of an SAPUI5 application

Seeking a Solution Is there a way to integrate the three.js library into SAPUI5 in order to access it using THREE as the root variable in my main view controller? I attempted to create a directory named libs within my project folder and include it in the ...

Is there a way to obtain the "rotated" coordinates of a mouse click within a canvas element?

Exploring New Features Within my image editing software, there is a canvas where users can draw shapes. These shapes are sent to a server and added to an XML file, which is then returned to the client for display. Now, I am looking to enhance the program ...

Unable to call Ionic component function using ref in Vue3

I'm attempting to utilize the closeSlidingItems method of the IonList element in order to automatically close the sliding item after clicking a button that appears from behind once the item is slid to the right. My approach involved referencing IonLi ...

Step-by-step guide on replicating a website along with its CSS styles and scripts

I've been exploring the idea of cloning a webpage, such as Instagram's login page, along with its CSS elements and JavaScript, to use locally. Basically, I want to duplicate the login page and host it on my test server in a way that allows it to ...

Tips for concealing a chosen alternative from the menu of options when utilizing mat-select

I am currently working with the latest version of mat-select, version 16. I have a requirement where, when a specific option is selected and the select drop-down is clicked again, that selected option should not appear in the options list. Below is the HTM ...