What is the distinction between using localStorage and storing individual files when clicking?

Recently, I created a basic jQuery script that stores values such as "voted1", "voted2", and "voted3" in localStorage. However, I encountered an issue where all values are stored simultaneously on click, whereas I require them to be stored individually per click for future jQuery operations (for example, initiating jQuery logic if "value3" is present).

Despite weeks of experimentation, I have been unable to resolve this dilemma.

Below is the HTML:

[gallery link="none" size="medium" ids="102,13,27,25,23,15" orderby="rand"]
<div class="exists" style="display: none;">Thank you for voting!</div>

CSS:

.gallery-item a {
    // CSS styles here
}
.exists {
    // Additional CSS styles here
}
.voted {
    // More CSS styles here
}

And here's the jQuery code snippet:

$(document).ready(function() {
    var voteLink = $('.gallery-item a');
    var votedYes = $('.exists');
    voteLink.one('click', function() {
        // jQuery action on click
    })
});

Does anyone have any insights into how I can save these values separately in localStorage on each click?

Thanks a lot!

Answer №1

  $(document).ready(function() {
    var voteLink = $(".gallery-item a");
    var votedYes = $(".exists");
    if (localStorage.getItem("count") === null) {
      localStorage.setItem("count", 1)
    }
    if (!(localStorage.getItem("voted3") === "yes3")) {
      var x = Number(localStorage.getItem("count")),
        func = function(e) {
          if (x < 3) {
            localStorage.setItem("voted" + x, "yes" + x);
            $(this).text("Thanks for voting " + x)
              .addClass("voted" + x);
            localStorage.setItem("count", 1 + x);
            x = Number(localStorage.getItem("count"));
          } else {
            localStorage.setItem("voted" + x, "yes" + x);
            $(this).text("Thank you! for vote " + x)
              .addClass("voted" + x)
              .fadeOut("slow");
            if (localStorage.getItem("voted3") === "yes3") {
              voteLink.remove();
              votedYes.fadeIn(1800);
            }
          }
        };
      voteLink.on("click", func);
    } else {
      // perform actions if `localStorage` has the key `"voted3"` with value `"yes3"`
    }
  })

Answer №2

Please Note: While attempting to answer your question, it is important to acknowledge that the solution provided may not be accurate due to insufficient details about your specific use case. However...

The code below makes certain assumptions, including:

  • LocalStorage will store up to 3 votes
  • In order to cast vote n+1, vote n must have been previously recorded

You can either set handlers based on localStorage content:

if (
      localStorage.getItem("voted1")
   && !localStorage.getItem("voted2")
) {
     voteLink.one('click', function() {
         localStorage.setItem('voted2', 'yes2');
         //...
     });
}

...or check localStorage within your event handler:

fn_vote2 = function() {
    if (
          localStorage.getItem("voted1")
       && !localStorage.getItem("voted2")
    ) {
        localStorage.setItem('voted2', 'yes2');
        //...
        voteLink.off('click', fn_vote2);
    }
};
voteLink.on('click', fn_vote2);

Applying the same method for vote1 and vote3 should be straightforward. Keep in mind that this approach involves registering a handler for multiple events rather than just one, as it is removed upon successful completion.

One benefit of this technique is the ability to conduct cascade voting without needing to reload the page.

Lastly, considering that localStorage persists across sessions, it is recommended to avoid using generic keys like vote<n>.

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

Tips for resolving the issue of invalid functions as a child component in React

When I call a function that returns HTML code, everything works fine until I try to pass a parameter in. At that point, I receive an error saying "Functions are not valid as a React child." The issue is that I need to access the props from this function. T ...

The HTML page is failing to call the function in the JavaScript application

I recently started taking a YouTube Javascript course on chapter 34 titled "Make start button work" Javascript tutorial My HTML, CSS, and Javascript files are all located in the same folder. I am using VS Code along with the Live Server extension for codi ...

Using the mpdf addPage function generates new empty pages

Hey there, I'm facing an issue where using $mpdf->addPage() within a for loop results in creating blank pages instead of adding content. My goal is to generate a new page when a certain condition is met and then populate it with the required conten ...

Iterate through the JSON response once the AJAX call is successful

Apologies for the duplication, this question was originally asked on Stack Overflow, but as a newcomer to this topic, I am seeking guidance on how to achieve it? Below is my AJAX call: $("#btnprocess").click(function () { $.ajax({ ...

Resolving the ENOTFOUND error in Imgur API call: 443

I keep getting the same error message every time I execute the node.js code below. As someone who is new to working with Authorization Headers in node.js, I must be overlooking something. Can someone offer assistance or direct me to reliable documentatio ...

Tips for delaying page rendering until an AJAX call finishes

While AJAX calls are known for allowing the rest of a page to load before a certain element is ready, I have a unique business requirement that complicates things. I am mandated to use AJAX due to the architecture in place. However, I cannot give the appe ...

What are the steps to utilize chrome.tabs.onUpdated.addListener?

I am currently working on a Chrome extension where I need to display an alert() showing the page URL whenever the user switches tabs or enters a new URL in a tab. However, my current implementation is not functioning as expected: chrome.tabs.onUpdated.ad ...

Names of VueJs components

Currently, I am coding in VueJS and encountering the following scenario <li @click = "selectedComponent = 'appManagment'"><i class="ion-clipboard"></i>Management</li> My goal is to have the name displayed as {{selectedCo ...

An error stating 'THREE.OBJLoader is not a constructor' has occurred, along with an 'Unexpected token {' message in OBJLoader and OrbitControls

Attempting to showcase an OBJ 3D model as a wireframe that can be interactively moved using OrbitControls in Three.js. Being new to three.js, I apologize if I'm overlooking something obvious. Successfully displayed a wireframe cube with OrbitControls ...

Changing the height of a Bootstrap 3 row without using less variables

Can someone please explain how to adjust the .row width in Bootstrap so that the col grid still functions correctly, but certain .rows are tighter than default? Thank you. ...

Enhancing Your Website - Customizing Image Sizes for Optimal Display

I have put in a fair amount of effort searching through Google and attempting to troubleshoot the issue on my own, but despite my limited knowledge, I am unable to determine how to properly scale my image using bootstrap. Essentially, I have two flex boxe ...

JavaScript - Toggle Checkbox State Based on Array Values

Currently, I'm in the process of building a Laravel user management system for a project. This system will allow admins to edit any selected user who is registered on our website. Upon clicking the edit button, a modal form containing the user's ...

Automatically assigning IDs to all elements on an Angular webpage

We are currently developing an enterprise web application and have brought on board an e2e test engineer to automate tests. The test engineer has requested that we assign IDs to all elements in our pages. Is there a tool or method available to automatical ...

Notifying users with a beeping sound in PHP through AJAX queueing

I am currently developing a Queuing system for my helpdesk support platform. I am facing an issue with detecting changes in the input value. I want to trigger the play_sound() function every time the input value increases. The current value of the input is ...

Having trouble centering an element with Bootstrap's offset feature in CSS

Here is the HTML code I am working with: <div id = "search_form" > <h1> Looking for travel ideas? </h1> <div class="input-group"> <form action="" method="get" id = "search-form" > {% csrf_token %} ...

Steps to trigger an alert when the entered quantity exceeds the current stock levels

After developing an IMS System, I encountered a problem where my stock is going into negative figures. To resolve this issue, my primary goal is to trigger an alert whenever the quantity entered by a user exceeds the available stock. For example, if a us ...

Trouble with HTML5 Geolocation Functionality

I am having an issue with my Geolocation code. It works fine when I run it on my desktop, but when I upload it to a free hosting service like [http://darkdays.byethost14.com/cc.html], the button does not work and nothing pops up. Can anyone help me trouble ...

How to perfectly align a full-width div with a div of specific width

Consider this scenario: .d1 { width: 100px; float: left; } .d2 { width: auto; float: left; } <div class="d1">Fixed Content</div> <div class="d2">This content should expand to fill the rest of the page vertically.</div> This setu ...

How to dynamically change the class of an element that contains other elements using JavaScript and JQuery

I have created a blog archive with the following format: +Year +Month Title Here is a snippet of the code: <ul> <span class="toggle">+</span> <li class="year">$year <ul> <span ...

What are the steps for positioning the footer at the bottom of the page?

Need help positioning a footer at the bottom of the page? Using the class fixed-bottom causes the footer to overlap the content when scrolling. <div class="sticky-top"> <qipr-header></qipr-header> <qipr-sidenav>&l ...