Creating a "Mark as Read" function using localStorage

Looking for a solution to persist the state of "Mark as Read" or "Mark as Unread" even after refreshing the page? Want to use localStorage to save this data? Here's an example of code snippet for toggling between these states:

function readunread() {
    currentvalue = document.getElementById("readunread").value;
    if(currentvalue == "Mark as Unread"){
      document.getElementById("readunread").value = "Mark as Read";
    } else{
      document.getElementById("readunread").value = "Mark as Unread";
    }
}
body {
    background:black;
}
.button {
    border: none;
    color: white;
    font-family: Corbel;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    background-color: black;
}

input[type=button] {
    font-size: 20px;
    font-family: Corbel;
    text-decoration: none;
    color: white;
    border: none;
    background: none;
    cursor: pointer;
    margin: 0;
    padding: 0;
}
<input type="button" value="Mark as Read" id="readunread" onclick="readunread();">

Clicking "Mark as Read" changes it to "Mark as Unread", but the change is not preserved after page refresh. How can you ensure it stays in its latest state?

Answer №1

To implement the changes in your scripts, there are two key modifications required:

<script>
  function adjustStatus() {
    currentValue = document.getElementById("status").value;
    if (currentValue == "Mark as Inactive") {
      document.getElementById("status").value = "Mark as Active";
      // 1. Update the local storage
      localStorage.setItem("status", "Mark as Active");
    } else {
      document.getElementById("status").value = "Mark as Inactive";
      // 1. Update the local storage
      localStorage.setItem("status", "Mark as Inactive");
    }
  }
</script>

<input
  type="button"
  value="Mark as Active"
  id="status"
  onclick="adjustStatus();"
/>

<script>
  // 2. Retrieve the stored value from local storage
  function initializeState() {
    const storedValue = localStorage.getItem("status");

    console.log(storedValue);
    if (storedValue == "Mark as Inactive") {
      document.getElementById("status").value = "Mark as Inactive";
    } else {
      document.getElementById("status").value = "Mark as Active";
    }
  }

  initializeState(); // Ensure to invoke the function
</script>

Answer №2

To efficiently manage the read/unread status of items using localStorage as the persistent data store, you must serialize the (un)read state into a string format for storage and then deserialize it upon retrieval since localStorage only supports string values. JSON serves as an optimal choice for serialization due to its ability to represent various JavaScript data structures and simple parse/stringify capabilities.

It can be challenging to demonstrate such functionality in a live code snippet on platforms like Stack Overflow due to restricted access to features like localStorage, which triggers runtime exceptions when attempted. However...

Below is a self-contained demonstration illustrating the storage of read/unread states for a list of items through basic functional programming techniques for organized code structure. This example comprises plain HTML + CSS + JavaScript without any external frameworks like React. You can easily copy + paste this code into a local HTML file on your computer and run it using a local static file server (e.g., Deno or Python) to witness its functionality. Detailed comments are included throughout to guide you through each step of the program execution.

If you wish to inspect the state of your localStorage during testing, refer to the question How to view or edit localStorage?.

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />

  <title>LocalStorage: read/unread items</title>

  <style>
    /* Sample styles for illustration purposes - styling customization can be applied */

    * { box-sizing: border-box; }
    body { font-family: sans-serif; }

    .toggle-status {
      font-size: 1rem;
      padding: 0.25rem;
      width: 8rem;
    }

    #list {
      list-style: none;
      padding: 0;
      display: flex;
      flex-direction: column;
      gap: 0.5rem;
      align-items: flex-start;
    }

    .item {
      display: flex;
      gap: 1rem;
      align-items: center;
    }

    .item.read > .item-content { font-weight: normal; }
    .item.unread > .item-content { font-weight: bold; }
  </style>

  <script type="module">
    // Functions to handle read/unread item states stored in localStorage
   
    // Ensure proper storage and retrieval of read/unread item states
    

    // Update the read/unread status for a single item
  

    // Toggle between read/unread status for an item
  
   
    // Invocation function
    
   
  
  </script>
</head>

<body>
  <!--
    List of items with unique IDs, toggle buttons,
     and text contents 
  
    -->
  <ul id="list">
    <li class="item" data-id="cc9e88ce-3ed4-443a-84fc-fa7147baa025">
      <button class="toggle-status">Mark as read</button>
      <div class="item-content">First item content</div>
    </li>
    <li class="item" data-id="23a9204c-905f-48db-9f6a-deb3c8f82916">
      <button class="toggle-status">Mark as read</button>
      <div class="item-content">Second item content</div>
    </li>
    <li class="item" data-id="18b47e4c-635f-49c0-924e-b9088538d08a">
      <button class="toggle-status">Mark as read</button>
      <div class="item-content">Third item content</div>
    </li>
    <li class="item" data-id="ed2aacca-64f0-409d-8c1b-d1bdcb7c6058">
      <button class="toggle-status">Mark as read</button>
      <div class="item-content">Fourth item content</div>
    </li>
    <li class="item" data-id="0fce307b-656a-4102-9dc9-5e5be17b068d">
      <button class="toggle-status">Mark as read</button>
      <div class="item-content">Fifth item content</div>
    </li>
    <!-- ...etc. -->
  </ul>
</body>

</html>

Answer №3

Great job, you were almost there! The final step is to implement local storage in your code. Simply replace your current JavaScript with the snippet below:

// On Page Load
const readUnreadButton = document.getElementById("readunread");
document.getElementById("readunread").value =
  localStorage.getItem("readunread") || readUnreadButton.value;

// On Button Click
function readunread() {
  const readUnreadButton = document.getElementById("readunread");
  let currentValue = readUnreadButton.value;
  if (currentValue === "Mark as Unread") {
    readUnreadButton.value = "Mark as Read";
    localStorage.setItem("readunread", "Mark as Read");
  } else {
    readUnreadButton.value = "Mark as Unread";
    localStorage.setItem("readunread", "Mark as Unread");
  }
}

https://codesandbox.io/s/ecstatic-orla-7k81n8?file=/index.html

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

Having trouble accessing the dashboard after uploading a document to Firestore

I am currently working on a project where I need to upload an audio file to Firebase storage and also add document data related to the audio file in Firestore database. The process involves recording the audio, uploading it to Firebase storage, submitting ...

What is the process of handling the event queue in Node.js?

Exploring the intricacies of the Node.js architecture has left me with several questions: 1) Is the event loop a component of libuv or v8? 2) How does the callback in the event queue transition to the call stack for execution after being delegated by the ...

JavaScript multiplying an array in HTML

Snippet of HTML code <input name="productCode[]" value="" class="tInput" id="productCode" tabindex="1"/> </td> <input name="productDesc[]" value="" class="tInput" id="productDesc" readonly="readonly" /></td> <input name="pr ...

Transform or retrieve information from input into unformatted text

I'm working on a JavaScript function that can convert input values to text. However, I am facing an issue as I only want to convert data from one specific row into plain text. Each row in my table has 5 cells along with a button for saving the data. I ...

Switching code from using .hover() to using .click() while still maintaining the functionality of both.orChanging code to switch

How can I change this script to trigger on click and also maintain the hover functionality: $x = jQuery.noConflict(); $x(document).ready(function () { $x(".swatch-anchor").on('click hover', function () { var newTitle = $x(this).attr( ...

Using an In-Memory Isolated Neo4J Database to Test NodeJS Applications

Can anyone suggest a method to quickly create small in-memory Neo4J database instances for testing NodeJS code with Jest? ...

Having numerous profiles open could lead to ultimately controlling just one - selenium

I'm developing a unique application that empowers users to automate a process across multiple chrome profiles simultaneously. However, I am encountering an issue where the actions performed on each profile are only affecting one. Within my main scrip ...

Iterate through the call feature repeatedly, ensuring that each call has a different iteration number assigned to a variable within the

I have a situation where I need to call a certain feature (which has validations) multiple times within a loop. Currently, my code successfully calls the feature 3 times. * def xxx = """ function(times){ for(i=0;i<times ...

Transferring Data from Extension to Webpage for the First Page Load - Firefox

Developing an extension for browsers like Chrome and Firefox. As per our requirements, we need to transfer some stored information from the extension to the webpage during page load. This data should be available on the webpage before any XHR request is tr ...

Uploading files with previews and no option to alter the image dimensions

I am having trouble with resizing an image preview before submitting it. Despite setting the width and height to 1px in both the div and image, it still displays at its normal dimensions. $(function() { var imagesPreview = function(input, placeToIns ...

Utilizing and transmitting contextual information to the tooltip component in ngx-bootstrap

I am currently working on integrating tooltips in ngx-bootstrap and trying to figure out how to pass data to the ng-template within the tooltip. The documentation mentions using [tooltipContext], but it doesn't seem to be functioning as expected. Belo ...

The situation arose where Next.js could not access the cookie due to

Hi there, I'm new to web development and recently encountered a challenge with my next.js app. I'm currently following Brad Traversy's course on udemy to learn basic CRUD functions. In this component, I am trying to fetch user data from my ...

Continual dark mode throughout page navigation with the ability to switch between light and dark modes

I've been experimenting with creating a persistent dark mode feature for web pages. My goal is to remember the user's preference as they navigate between pages. Additionally, I included a toggle button for switching between dark and light modes t ...

Toggle button in React following a list iteration

Upon receiving data from an API call to Google Books, I want to hide the description paragraphs and implement a toggle button using the "hidden" CSS class from Tailwind CSS. Currently, I am just logging the elements on the "view description" button and uns ...

Having trouble implementing CORS in a Slim API

I'm facing challenges in setting up CORS with Slim and AngularJS. AngularJS HTTP Request: $http({ method: 'GET', headers: { 'Content-Type': 'application/json', Accepts: 'application/json&ap ...

Running multiple web applications with different base directories on a single Express server

I am currently working on serving a website that requires different static directories for various routes. When a GET request is sent to the /tools* route, I want to utilize the /dist/toolsApp/ directory as the base directory for my frontend code. If ...

Exploring the world of jQuery: Toggling radio buttons with variables on click

On the right side, there is a table of data that initially contains certain values, but can be modified using radio buttons and a slider on the left. If you select the first radio button for the "pay in full" option, it will increase the estimated discoun ...

The SVG image exceeds the boundaries of the parent column div in bootstrap

I am struggling to make a SVG fit inside a column in a bootstrap div with col-lg-4. I tried using img-fluid, but it did not work as expected. The SVG should automatically adjust its size to fit the parent div. However, that is not happening. .star-ratin ...

What is the best way to update the text within a Span element as the user moves through the Jquery slider?

Can I utilize jQquery to dynamically alter the text content of my "video_box_label" span element based on the active slide in my "flexslider" slideshow? For instance, when the slideshow transitions to the second slide, I want the text to change from "Mee ...

Why is it that GetElements does not provide immediate results upon execution?

Just diving into the world of Javascript for the first time and experimenting with it on Chrome, but running into unexpected results. When I try: document.getElementsByTagName("h1") I anticipate seeing: <h1>tester h1 in body</h1> Instead, wh ...