Disable the button if the LocalStorage does not have any data stored

In my current setup, I have a list of words that users can interact with by clicking on a heart icon to store the word in localStorage. Once the first word is added, a red button at the top of the page becomes active, which will eventually link to the favorites page.

For those interested, here is the working code:

https://codepen.io/20201015/pen/LYZGKNv

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<div class="container" style="margin:20px;">

  <a class="btn btn-sm btn-danger" id="success" href="#" disabled="disabled" style="pointer-events: none;"><i class="fa fa-heart"></i> View</a>

  <div class="scrollbox list" style="background:#000;">
  <ul class="list-unstyled">
    <li id="fairunmuzzled">fairunmuzzled</li>
    <li id="illusionpat">illusionpat</li>
    <li id="impureblossom">impureblossom</li>
    <li id="arousedsolemn">arousedsolemn</li>
    <li id="bamboopeeves">bamboopeeves</li>
    <li id="mudrubbish">mudrubbish</li>
    <li id="rickshawobject">rickshawobject</li>
  </ul>
  </div>

<a href="#" onclick="localStorage.removeItem('jpxun');" class="btn btn-warning"><i class="fa fa-trash"></i> Delete Local Storage</a>

<p>If delete all, refresh page to see that the red button is inactive again.</p>
   
</div>

Javascript

var ct = 0;
var jpxun = JSON.parse(localStorage.getItem('jpxun')) || [];

// Checking if usernames local storage item is populated

var MyUsernames = JSON.parse(localStorage.getItem('jpxun'));

// If it's populated, make the red button active

if (MyUsernames) {
    var elem = document.getElementById('success');
    if (elem) {
        elem.removeAttribute('disabled');
        elem.removeAttribute('style');
    }
}

// Counting elements
if (jpxun) { // Counting elements
    for (var i = 0; i < jpxun.length; i++) {
        ct ++;
    }
} else {
    ct = 0;
}

var lists = document.querySelectorAll('.list');

if (lists.length) {
  lists.forEach(list => {
    list.addEventListener('click', e => {
      if (!e.target.id) return;
      var id = e.target.id;
      var item = e.target;
      var temp = ct++;
      var newCt = "" + temp + ""; // ID must be wrapped in speech marks for deletion functionality to work
      var findme = jpxun.findIndex(e => e.name == id);
      
      // Adding word to localStorage
      
      if (findme == -1) {
        jpxun.push({ id: newCt, name: id });
        item.className = 'fav';
        var elem = document.getElementById('success');
        elem.removeAttribute('disabled');
        elem.removeAttribute('style');
        
      // Removing word from localStorage
        
      } else {
        jpxun.splice(findme, 1)
        item.className = 'nofav';
      }
      localStorage.setItem('jpxun', JSON.stringify(jpxun));
    });
  });
}

The code works fine despite any errors or bad practices present within it.

I am currently trying to figure out how to disable the red button in the JavaScript section when localStorage is empty:

// Removing word from localStorage
        
      } else {
        jpxun.splice(findme, 1)
        item.className = 'nofav';
      }

I understand that in order to delete the entire localStorage and deactivate the red button if no items are left, I need to:

  1. Count the remaining elements after deleting a word.
  2. If there are no items left, delete the entire localStorage using
    localStorage.removeItem('jpxun');
    and change the CSS of the red button to make it inactive.

I've attempted various solutions without success, so I would appreciate any advice or suggestions from the community on how to achieve this goal.

Answer №1

Alright, so you have a few tasks to handle:

1 - In order to disable the red button when localStorage is empty, simply check if there is any data in localStorage. If not, set the disabled attribute to true as shown below:

// For demonstration purposes, I am creating a dummy local storage object here. You can ignore this.
const localStorage = { getItem: () => false }

let buttonEnabled = false

if (localStorage.getItem("jpxun")) {
    buttonEnabled = true
}

document.getElementById('fav').setAttribute("disabled", buttonEnabled)
<button id="fav">PRESS ME ! </button>

2 - When deleting a word, count the number of elements left by checking the length after splicing:

let numberOfElements = jpxun.length
else {
        jpxun.splice(findme, 1)
        numberOfElements = jpxun.length
        item.className = 'nofav';
      }

3 - If there are no items left, delete the entire localStorage using localStorage.removeItem('jpxun'); and change the CSS of the red button to make it inactive.

The approach for the first task can be applied in the main function. Revisit it to ensure that there are no remaining items before performing the deletion on localStorage.

 localStorage.removeItem('jpxun');

Answer №2

The stored data is saved in the browser's localStorage under the key jpxun. To check if it exists and contains any JSON data, you can use the following approach:

This is how I would handle it:

if(typeof localStorage.jpxun == "undefined" || 
Object.keys(JSON.parse(localStorage.getItem('jpxun'))).length<1){
    // ...
}

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

Modify individual list item attributes

I have been attempting to modify the background of the list item labeled as home in order to ensure that it displays hover properties even when not being interacted with. Despite specifying this in the class, the appearance does not change. Below is the H ...

JS unable to insert new row in table

I checked the input value before submitting it in the form and confirmed that it is correct, returning as a string.enter image description here const saveList = () => { const inputListNameText = inputListName.value; fetch('/api/lists' ...

Enhance the Search Box with a Vibrant Glow Effect When in Use

I need help adding a glow effect color around a search field when a user clicks on it to type. I want the border to have a shadow and the glow effect to be orange. I have included the CSS below, but I'm unsure of what to change or add. Any assistance ...

Warning: Next.js is throwing a hydration error because the server HTML does not include a matching <main> element within a <div>

I have been encountering hydration issues in my next.js application. After extensive troubleshooting, I have found that the culprit might be the higher order component called withAuth.js The error message displayed is: Warning: Expected server HTML to con ...

Modifying `<a>` tag attributes in HTML with JavaScript by detecting checkbox selections

As a newcomer to JavaScript, I am seeking some assistance and ideas. I have an HTML anchor tag that I would like to modify or add attributes to based on checkbox selections. Anchor tag with no checkboxes selected: <a href="javascript:void(0)" data-cb ...

What is the best method to place files from a file input into an array in the Firefox browser?

(I am using Vue 3) I have a functionality where I add files from an input file to an array, and then conditionally render these file names. Everything works perfectly on Chrome, but I encountered an issue with Mozilla Firefox. In Firefox, the array of file ...

Firestore javascript query is returning empty results

Yesterday everything was working smoothly, but this morning it suddenly stopped moving forward. The Firestore query is not returning anything - no errors, no response. Surprisingly, the console displays the phone perfectly fine. Additionally, the phone n ...

Obtain information transferred in the request through AJAX within the HTTP Response from Node.js

I have a scenario where I am sending multiple AJAX requests by looping through a split string and need to associate each response with the corresponding request. My goal is to capture the data sent in the HTTP response of each AJAX request because these re ...

Choose and display a specific set of data from a JSON array

On this particular link, there is an array containing 100 sets of values. I have exhausted my brain trying to figure out how to access and display the "percent_change_24h" value for only the first 0..10 sets in order to calculate the average. <script&g ...

Using Sweetalert2 to send data via AJAX POST request

Recently, I've been incorporating SweetAlert2 into my project and I want to create an "Add Note" feature. The process involves the user clicking a button, being directed to a page, and then the following script is executed: <script>swal({ ...

Using Observables to assign values received from API calls to each element during loop iterations

As I loop through using a foreach loop, I need to call functions that will make async API calls and return values to be rendered in the HTML. The first function getCurrentValue() will return the currentTemperatureRef which should then be assigned to recei ...

Tips for organizing divs once another div has been hidden using jquery

I am working towards implementing a live result filter feature. There are three filters available: Good fit, bad fit, and scheduled. When the "Good fit" filter is clicked, it should display panels with the class "good_fit_panel". Let's assume there ar ...

Tips for loading images dynamically (or lazily) as they come into the user's view with scrolling

Many modern websites, such as Facebook and Google Image Search, display images below the fold only when a user scrolls down the page enough to bring them into view (even though the page source code shows X number of <img> tags, they are not initially ...

Is there a way to ensure that a div automatically moves below the main div when it reaches its full length?

I am facing an issue with a foreach statement in jQuery where I am generating Bootstrap cards for each product in a list. The problem arises when attempting to create multiple cards in a row, as the width of the cards becomes too small for the content. I ...

The compilation of the module has encountered an error with the PostCSS loader. There is a SyntaxError at line 2, character 14 indicating an unknown

I am developing an Angular 8 application. Currently, I am incorporating AlertifyJs into my project. In the styles.css file of Angular, I have imported these libraries: @import '../node_modules/alertifyjs/build/alertify.min.js'; @import '. ...

Tips for achieving a slanted div design

Is there a way to create a slanted div similar to the red div shown on this website? Below is the CSS I have attempted: #parallelogram { width: 150px; height: 100px; -webkit-transform: skew(20deg); -moz-transform: skew(20deg); ...

Invoke functions once the animation has finished

My current issue is as follows: I am trying to call two functions after an animation has completed. I have achieved calling one function using the provided example, but I need to call one more function as well. Here is the sample code: $('.content& ...

Transfer all image files from Node.js to the frontend

What is the best way to send all image files from my backend nodejs server folder to my Reactjs client? I have set up a website where users can sign in and upload their files. However, I am facing an issue where only one file is visible on the client side, ...

What is the process for invoking a method that accepts a List<string> type parameter through an ajax call

I have been trying to figure out how to make an AJAX call to a C# method from jQuery, but it seems that the code below is unable to send the value to the "SessionTemplate(List list)" method. How can I successfully pass a value of type List? [HttpPost] pub ...

When I click the button, I would like the value of the button to be displayed in a textbox

I'm currently working on an interactive virtual keyboard project and need help with a function that will display the pressed button values in a text box located next to the keyboard. Here is the code snippet I've come up with so far: <script ...