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

Rules for validating string and numeric combinations in Vuetify are essential for ensuring accurate

Looking for guidance on implementing Vuetify validation to enforce rules (using :rules tag on a v-text-field) in the format of AB-12345678 (starting with two letters followed by a hyphen and then an 8-digit number). I'm having difficulty achieving thi ...

JavaScript doesn't automatically redirect after receiving a response

Hey there, I'm attempting to implement a redirect upon receiving a response from an ajax request. However, it seems that the windows.href.location doesn't execute the redirect until the PHP background process finishes processing. Check out my cod ...

ability to reach the sub-element dictionaries in typescript

class ProvinciaComponent extends CatalogoGenerico implements OnInit, AfterViewInit { page: Page = new Page({sort: {field: 'description', dir: 'asc'}}); dataSource: ProvinciaDataSource; columns = ['codprovi ...

Tips for avoiding the display of concealed forms on a webpage

Hey there, I'm just starting out with html forms and currently experimenting with Jquery to hide forms upon loading the page. However, I've encountered an issue where some forms briefly appear before hiding after the page finishes loading. Here& ...

What is a more efficient method for incorporating optional values into an object?

Currently, I am utilizing the optional addition feature in this way: ...(!!providerId && { providerId }), ...(!!practiceId && { practiceId }), Is there a more elegant shorthand method to replace this logic, such as: yield createRemark ...

The placeholder attribute for input types does not display consistently across all browsers

I am experiencing an issue with the placeholder text in my input field. <input type="text" name='linkLabel{{index}}' autocomplete="off" class="input-large tight-form-url last remove-cross" required="required" placeholder="{{'linkLabel&ap ...

The positioning of the parent element shifts as a result of the CSS

What causes a vertical position change in buttons with content floated left or right? Take this example http://jsfiddle.net/8ff6dhou/ <button>aaa</button> <button><div style="float:left">bbb</div></button> <button> ...

I encountered an error stating "angular not found" when attempting to dynamically load my Angular scripts

My Angular application is running smoothly. However, I found it tedious to include multiple script tags in my HTML documents every time. To simplify this process, I decided to create a small script that would automatically generate the necessary tags for m ...

Customize DataTables to show specific rows with unique cell content and styling

We are currently using the jQuery DataTables plug-in and have encountered some limitations. Despite overcoming two major challenges, we are now facing a third issue: Within our table, we need to include a distinct row that serves as a visual separator bet ...

Uncovering secret divs with the power of jQuery timing upon reload

Currently, I am in the process of developing a custom Wordpress theme for my blog which includes an overlay-container. When a button is clicked, this container slides in from the top and pushes down the entire page. To achieve this functionality, I am uti ...

Using Jquery AJAX to Submit an HTML Form

Trying to use AJAX to submit an HTML form using this specific example. The code for the HTML form: <form id="formoid" action="studentFormInsert.php" title="" method="post"> <div> <label class="title">First Name</label> ...

Dealing with transformed data in AngularJS: Best practices

Scenario I have a dataset structured like: [{ xRatio: 0.2, yRatio: 0.1, value: 15 }, { xRatio: 0.6, yRatio: -0.3, value: 8 }] I need to convert this data into absolute values for display in a ng-repeat. However, when I attempt to do so usin ...

Peer-to-peer Ajax image sharing

Currently, I'm utilizing Ajax to fetch images from a remote server. Initially, I attempted this by directly using the URL of the remote server - resulting in the returned image being a string (given that's how Ajax communicates). To rectify this, ...

Dealing with a checkbox click event in Vuejs when there is no parent element involvement

In the table below, you can see checkboxes displayed as images: example image of a table with checkboxes Here is an example code snippet: <tbody> <tr @click="goDetail"> <th scope="row><input type="checkbox" /></th> <t ...

Preventing the Rendering of Inline-Block Whitespace in Web Browsers

Essentially, in my attempt to create a four-column layout, I have the following HTML code: <div> <div>A column</div> <div>A column</div> <div>A column</div> <div>A column</div> </div ...

Styling the TinyMCE Toolbar within a Div container

While working on creating a unified TinyMCE toolbar that is fixed at the top of multiple containers within a div wrapper, I encountered an issue where the CSS styling of the toolbar was lost after wrapping. The toolbar only displayed hyperlink URLs inste ...

What is the best way to ensure the footer remains in an automatic position relative to the component's height?

I am struggling to position the footer component correctly at the end of my router-outlet. After trying various CSS properties, I managed to make the footer stay at the bottom but it acts like a fixed footer. However, I want the footer to adjust its positi ...

Unable to scroll following an ajax request

I am encountering an issue where I need to make an ajax call that populates a DIV and the content becomes as long as 2 web pages. However, I am unable to scroll unless I resize the window. How can I instruct the browser to recalculate the page content size ...

Error encountered while trying to eliminate array element

I have a project in the works that involves creating a page where users can filter suggestions and vote for their favorites. The screen is divided into 3 tabs: [Top Rated], [Newest], and [My Votes]. Upon loading the screen, a call to the database is made ...

Encountering issues with Monaco Editor's autocomplete functionality in React

I'm facing an issue with implementing autocomplete in the Monaco Editor using a file called tf.d.ts that contains all the definitions in TypeScript. Despite several attempts, the autocomplete feature is not working as expected. import React, { useRef, ...