Step-by-step guide on incrementally counting localStorage items using jQuery

After spending an excessive amount of time on this project, I have hit a roadblock. Despite days of testing, I am unable to achieve my desired outcome.

I am developing an image voting system that will track votes in localStorage. Since this is within WordPress, there isn't much HTML involved.

Below is the code snippet along with a brief explanation of each step:

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>

The .exists class within the HTML is designed to be displayed when certain jQuery criteria are met.

CSS:

.gallery-item a {
    background-color: black;
    border: 1px solid orange;
    border-radius: 6px;
    color: orange;
    display: inline-table;
    font-size: 14px;
    font-weight: bold;
    max-width: 100%;
    width: 32%;
}  
.exists {
    background-color: black;
    border-radius: 18px;
    box-shadow: 1px 3px 20px -3px grey inset;
    display: block;
    height: 32%;
    left: 24%;
    margin-left: 10%;
    margin-right: 10%;
    margin-top: 10%;
    max-width: 100%;
    padding-left: 12%;
    padding-top: 6%;
    position: fixed;
    top: 23%;
    width: 36%;
    z-index: 999999;
    color: olivedrab;
    font-weight: bold;
    cursor: context-menu;
}
.voted {
    background-color: green !important;
}

This should provide clarity on the design.

jQuery:

$(document).ready(function() {
    var voteLink = $('.gallery-item a');
    var votedYes = $('.exists');
        voteLink.on('click', function() {
            event.preventDefault();
            localStorage.setItem('voted1', 'yes1');
            $(this).text('Thank you!');
            $(this).addClass('voted');
            })
        });
$(document).read...

Despite logging all votes in localStorage (as 'voted1', 'voted2', and 'voted3') upon the first click, an unintended logic continues to unfold due to the triggering of "voted3." How can I prevent this? Is it possible to store the value only upon clicking?

Your insights would be greatly appreciated.

Answer №1

give this a shot

if (localStorage.getItem("voted4") == "yes4") {
        voteButton.remove();
        votedYes.fadeIn(1500);
      localStorage.setItem("voted4","remove1")
}

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

The note-taking app's JavaScript code does not currently have the capability to store notes in local storage

const noteContainer = document.querySelector(".note-container"); const createBtn = document.querySelector(".btn"); let notes = document.querySelectorAll(".input-box"); function showNotes() { noteContainer.innerHTML = localS ...

jQuery seems to be malfunctioning and throwing an uncaught TypeError

Encountering an error while running the jQuery code (as seen in Chrome debug): Uncaught TypeError: Cannot read property 'files' of undefined at HTMLInputElement.<anonymous> (Request.aspx:29) at HTMLInputElement.dispatch (jquery-2.2 ...

Issue with event stopPropagation() or stopImmediatePropagation() not functioning in Bootstrap 5

I'm attempting to implement a span tag with a click event within my according header, however, I don't want to display or collapse my according element. So, I tried using stopPropagation() and stopImmediatePropagation(), but neither worked. H ...

Performing Batch Writes in Firestore using the Admin SDK

I have a massive ASCII flat file containing 1.5 million lines, which is essentially a list of parts from a manufacturer. I want to store this data in Firestore. Originally saved as a .csv file, the size was 250GB. After converting it to a JSON file using ...

How to identify the node with the appropriate date range attribute using JavaScript or jQuery

I am seeking assistance in using Javascript, preferably jQuery, to identify the specific "node" within an XML structure where a given date falls between its "begin" and "end" dates. XML EXAMPLE: <nodes> <node begin="2014-01-01" end="2014-01- ...

Appending void elements to a list of references in React

I'm working with the code below: const nodeRefs = useRef<Array<HTMLDivElement | null>>([]); function setNodeRefs(ref: HTMLDivElement | null, idx: number): void { nodeRefs.current[idx] = ref; } {nodes.length === 5 && nodes.map((no ...

What is the exact position of Material UI's Grid item?

The CSS grid layout's grid-column property allows for specifying the location of grid items (e.g. grid-column: 1 / 3) I am looking to achieve a similar outcome using Material UI's Grid component, but it seems that I can only determine the number ...

What is the best way to organize two separate arrays based on a single shared variable?

I have two separate arrays containing information. One array includes the title of each national park and other related data, while the second array consists of alerts from the entire NPS system. The common factor between these arrays is the parkCode. How ...

Struggling to achieve the desired layout in the navigation code using CSS Grid. I am aiming for it to occupy the entire width of the screen

I'm facing an issue with customizing my HTML layout using grids. I want my nav element to occupy the entire available width. Below is my current code: header { text-align: center; grid-area: header; border: solid; } #nav1 { text-de ...

Challenges arising from utilizing distinct list style types for both parent and child elements with the assistance of CSS List

I am experimenting with the CSS counter reset feature to create a numbering system on my website. The main list should be in regular decimal format (e.g. 1, 2, 3, 4) while the sub-list should be in upper Roman numerals (e.g. I, II, III, IV, etc). Below is ...

Display the Ajax response in a designated div

I am facing an issue with my ajax code. It doesn't print any output, but when I use alert() to print the output, it shows up fine. $(".grp-ans").each(function(e){ $.ajax({ type: 'POST', url: 'show-answ ...

When the button is clicked, the JavaScript function is not being executed

I'm having a strange issue with my second button not working as expected. Despite appearing to be straightforward, the "Reset" button does not seem to be triggering the clear() function. Within the HTML code, I have two buttons set up to interact wit ...

Error: JavaScript alert not displaying

My asp.net page is not displaying the Javascript alert message until I clear the browser's cache memory. Can someone please explain why this happens and suggest a solution? ...

Encountered a MultiValueDictKeyError in Django at /employeeUpdate/ after making changes to the data

Encountering a django error "MultiValueDictKeyError at /employeeUpdate/ 'id'" after making changes to the data. Here is the code snippet from my views.py: def employeeUpdate(request): id = request.POST['id'] emp_username = requ ...

Issue with displaying entire object using Jest and console.dir

I'm having trouble displaying an error in my Jest test because it's not showing all the levels as expected. import util from 'util' describe('Module', () => { it('should display all levels WITHOUT util', () =& ...

The Div element seems to have a mind of its own, refusing

Check out my code on this link: http://jsfiddle.net/Pd7nm/ I'm trying to make the sidebar stop scrolling with the page once it reaches a certain point, but it just won't cooperate. I've attempted various solutions, but none seem to be effec ...

How to insert a value using jQuery Minicolors in an HTML document?

While I found similar topics on Stackoverflow, none exactly match my issue. I am currently incorporating jquery Minicolors into my project: https://github.com/claviska/jquery-miniColors/ Everything is functioning properly, but I simply need to accomplish ...

Retrieve items from an array using a series of nested map operations

When I execute the query below, it transforms the json data into objects - 1st level being a map (This works fine as expected) const customerOptions = () => { return customersQuery.edges.map(({ node: { id, name } }) => { return { key: id, text ...

Customize the color of individual columns on a Google Column Chart using JSON

Wondering how to set different colors for each column in a chart? Here's the code I'm using: var formDataKinder = {type:"Kinder"}; var jsonDataKinder = $.ajax({ type: "POST", data : formDataKinder, url: "./content/chartsData.ph ...

Angular 2 communication between parent and child components

I am having trouble incorporating an action button in the child_1 component, while the event handler is located in the sub child component, child_2. Here's a snippet of the code: app.component.html (Parent HTML) <div style="text-align:center"> ...