After the page is reloaded, apply a class to the divs by selecting them based on the "data" attribute

I have a set of four cards labeled "card", each representing different body parts: eyes, torso, arms, and legs.

<div class="card" data-lesson="eyes">eyes</div>
<div class="card" data-lesson="torso">torso</div>
<div class="card" data-lesson="arms">arms</div>
<div class="card" data-lesson="legs">legs</div>

Whenever the user clicks on a card, that specific card receives the designation of "reading". Furthermore, the browser captures the data attribute value from the clicked card and stores it locally in an array.

$(".card").click(function(){
    $(this).addClass("reading")
    localStorage.setItem("readingCards" , readingCards)
 });

My goal is to ensure that post-reload, any card matching a stored data attribute in the array will automatically be assigned the "reading" class, allowing for consistent visual cues even after page refreshes.

Answer №1

To efficiently loop through all elements that have the card class, utilize the each() function to verify if the respective data attribute is present in the locally stored string separated by commas.

Give this approach a try:

https://jsfiddle.net/kL8p9ec7/2/

$(document).ready(function(){

var readingCards = localStorage.getItem("readingCards")!==null?localStorage.getItem("readingCards"):'';

     $(".card").each(function(){

          if(readingCards.includes($(this).data("lesson"))){
            $(this).addClass("selected");
       }

     });

     $(".card").click(function(){

         $(this).addClass("selected");

         if(!readingCards.includes($(this).data("lesson"))){

         readingCards+=(readingCards.length>0?',':'')+$(this).data("lesson");
         localStorage.setItem("readingCards",readingCards);

    }

 });

Answer №2

Give this a shot-

The HTML code is as follows:

<div class="card" data-lesson="eyes">Card 1</div>
<div class="card" data-lesson="torso">Card 2</div>
<div class="card" data-lesson="arms">Card 3</div>
<div class="card" data-lesson="legs">Card 4</div>

The corresponding Javascript appears below:

// When the page loads, retrieve local storage items and display readings
var readingCards = localStorage.getItem('readingCards');
readingCards = typeof readingCards === 'string' && readingCards.length > 0 ? JSON.parse(readingCards) : [];

if (readingCards.length > 0) {
    $('.card').each(function(index) {
        let lesson = $(this).data('lesson');
        if (readingCards.indexOf(lesson) > -1) {
            $(this).addClass('reading');
        }
    });
}


$('.card').on('click', function() {

    if (!$(this).hasClass('reading')) {
        $(this).addClass('reading');
    }

    let lesson = $(this).data('lesson');

    if (readingCards.indexOf(lesson) === -1) {
        readingCards.push(lesson);
    }


    localStorage.setItem('readingCards', JSON.stringify(readingCards));
});

Answer №3

To distinguish the cards during the iteration of stored values, you can utilize the css selector ".card[data-lesson='AAA']".

let savedCards = localStorage.getItem("readingCards") || "";
savedCards = savedCards.split(',');
$.each(savedCards, function( index, cardValue ) {
   $(".card[data-lesson='" + cardValue + "']").addClass("reading");
});

Answer №4

To simplify the process, store the data as an array in local storage and then use a loop to easily set the class by selecting items based on their attributes.

$(document).ready(function() {
  // Retrieve stored cards from local storage or initialize an empty array
  var readingCards = JSON.parse(localStorage.getItem('readingCards') || '[]');
  
  // Add classes to elements based on stored card values
  readingCards.forEach(function(value) {
    $('[data-lesson="' + value + '"]').addClass('reading');
  });
  
  // Add click event to cards
  $(".card").on('click', function() {
    // Toggle class of clicked card
    var card = $(this);
    card.toggleClass('reading');
    
    // Create an array of active cards
    readingCards = $(".card.reading").map(function() {
      return this.dataset.lesson;
    }).get();
    
    // Store updated array in local storage
    localStorage.setItem('readingCards', JSON.stringify(readingCards));
  });
});

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

Is it feasible to set a default value in an HTML input field that is not editable using JavaScript?

Is there a way to set a default value in an input field of HTML that is not editable, and then allow users to add additional text to it? For example, having 'AB' as the default and uneditable starting characters, followed by any numbers such as A ...

When I click the confirm button on Sweet Alert, I would like to update the database status from the default (pending) to confirmed

When I click on the confirm button in this sweetalert, I need assistance with updating the STATUS column in my database. Thank you for your help. swal({ title: 'Are you sure?', text: "You won't be able to revert this!", type: &a ...

Retrieve an object using a variable

Essentially, my question is how to extract a value from a variable and input it into a sequence. Being Dutch, I struggle to articulate this query correctly. var channelname = msg.channel.name; "description": `${config.ticketlist.channelname.ticketmessage} ...

Ways to swap out element within ViewContainerRef in Angular

I am currently expanding my knowledge of Angular and I have encountered a challenge regarding dynamically creating components and swapping them within a single container. Here is the setup: <ng-container #container></ng-container> Here are the ...

Executing a function in Angular 2 depending on the class assigned to a <div>

In my HTML code, I am using *ngFor to iterate through an array of messages. <div *ngFor="let message of messages; let i=index" [focused]="i === activeIndex;" [ngClass]="{'message-list-active': activeIndex === i }" (click)="onAddtoMessag ...

Sticky positioning causes elements to stick to the window as the

https://i.stack.imgur.com/nv3vU.png I am facing an issue with a position sticky block that can vary in height relative to the window size. Sometimes, the block is taller than the viewport, making it impossible to scroll to see all the content. Is there a ...

ajax with names that are alike

I've set up a text input field that searches for file names on my server. However, it currently requires an exact match to display the file. I'm looking for a solution that can show me files even if the input text isn't an exact match. Here ...

ng-class in AngularJS not interacting with Scope method

I am in the process of creating a new application. Here is how my index.html file looks: <html ng-app='myApp'> <body ng-controller='mainController'> <div ng-view> </div> </body> </html> My m ...

Issue with border radius in MUI 5 affecting table body and footer elements

Currently, I am diving into a new project utilizing React version 18.2 and MUI 5.10.3 library. My main task involves designing a table with specific styles within one of the components. The table header should not display any border lines. The table body ...

Error: Attempting to access the 'url' property of an undefined variable, despite specifically checking for its undefined status

Within my React application, I am utilizing the following state: const [functions, setFunctions] = useState([{}]); I have created a test to check if a specific property is undefined: if (typeof functions[functionCount].url !== "undefined") { ...

Troubleshooting Problems with Node JS Express, Passport JS, and Authentication on Android Devices

I am currently setting up a login system using Node JS Express and Passport, incorporating Passport's local strategy: . The database in use is MongoDB. An issue I'm facing is the inconsistency of successful logins (especially with 'User A&ap ...

Tips for handling CSS loading delays with icons in OpenLayers markers

When using openlayers (v4.6.4) with font-awesome as marker icons, the icons do not display upon first load (even after clearing cache and hard reload). Instead, I see a rectangle resembling a broken character. It is only on the second load that they appear ...

How to make views in React Native adjust their size dynamically in a scrollview with paging functionality

Has anyone successfully implemented a ScrollView in React Native with paging enabled to swipe through a series of images? I am having trouble making the image views fill each page of the scroll view without hardcoding width and height values for the image ...

Why is the responseText from XMLHttpRequest always stripped of tags in AJAX?

Whenever the server sends the XML string to the client using the XMLHttpRequest object, I noticed that when I insert the text inside the div tags, it appears without any tags. However, I actually need the XML tags to be present so that I can parse the cont ...

Sending input values to controller action parameters in CakePHP

I am working on an HTML form in which I need the URL output to be structured as follows: "example.com/mycontroller/action/mike/apple" Upon submitting the form using "post" method, the form values are not visible and can only be accessed through "_POST" ...

Transform a jQuery collection of 'multiple unparented elements' into a string

I needed to manipulate HTML by selecting elements and converting the entire object into a string so that I could use setContent() in tinyMCE. The issue arose when there was no parent element. During the conversion to a string, only the first element would ...

Here's a guide on using a button to toggle the display of password value in Angular, allowing users to easily hide

I have successfully implemented an Angular Directive to toggle the visibility of password fields in a form. However, I am facing an issue with updating the text displayed on the button based on the state of the input field. Is there a way for me to dynami ...

Using $stateParams injection for unit testing Angular applications with Karma

Here is the starting point for the controller code: angular .module('hc.hotelContent') .controller('NameLocationController', nameLocationCtrlFn); //Todo change hotelDataService nameLocationCtrlFn.$inject = ['$stateParams', &a ...

Angular - send multiple HTTP requests for the length of an array and combine the responses into one array

Exploring angular for the first time and dabbling with the trello API. I have an array containing some list IDs that I need to make HTTP GET calls for, equal to the length of the array. For instance, if there are two IDs in the array, then the HTTP call sh ...

Transferring User ID from Google Tag Manager to GA4 Problem

I'm currently working on a new project and adding some dummy data to the dataLayer of Google Tag Manager from the \_app.tsx file. <Script id="gtg" strategy="beforeInteractive"> { window.dataLayer = window.dataLayer || &b ...