Classes were successfully stored on the icon following the page's refresh

I'm struggling with the following code snippet:

   <div class="places-item">
      <div class="places-item-img"></div>
      <div class="places-item-header">
         <h2>Machu Picchu, Peru</h2>
         <div class="places-item-header-add"><svg xmlns='http://www.w3.org/2000/svg' width='512' height='512' viewBox='0 0 512 512'><path d='M352,48H160a48,48,0,0,0-48,48V464L256,336,400,464V96A48,48,0,0,0,352,48Z' style='fill:transparent;stroke:#000;stroke-linecap:round;stroke-linejoin:round;stroke-width:32px'/></svg></div>
      </div>
   </div>
   <div class="places-item">
      <div class="places-item-img"></div>
      <div class="places-item-header">
         <h2>Ciucaș Peak, Romania</h2>
         <div class="places-item-header-add"><svg xmlns='http://www.w3.org/2000/svg' width='512' height='512' viewBox='0 0 512 512'><path d='M352,48H160a48,48,0,0,0-48,48V464L256,336,400,464V96A48,48,0,0,0,352,48Z' style='fill:transparent;stroke:#000;stroke-linecap:round;stroke-linejoin:round;stroke-width:32px'/></svg></div>
      </div>
   </div>
.places-item {
    width: 100%;
}
.places-item-img {
    width: 100%;
    height: 350px;
  background-color: cyan;
}
.places-item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1em 0;
}
.places-item-header h2 {
    font-size: 24px;
    max-width: calc(100% - 38px);
}
.places-item-header-add {
    width: 28px;
    height: 28px;
    cursor: pointer;
}
.places-item-header-add svg {
    width: 100%;
    height: 100%;
}
.places-item-header-add.added svg path {
    fill: #000 !important;
}
var addBtn = document.querySelectorAll('.places-item-header-add');

for(i=0;i<addBtn.length;++i)addBtn[i].addEventListener('click',function(){
  this.classList.toggle('added');
});

After clicking on the icon, it should turn black. How can I ensure that the clicked icon remains black even after a page refresh? Would using localStorage be an ideal solution in this case?

Answer №1

Ensure that your elements are distinct by adding ids to identify the active item.

For instance, assign an id to your item header.

<div id='peru' class="places-item-header-add">

Upon loading the window, check the local storage value and update the item class accordingly.

var addBtn = document.querySelectorAll('.places-item-header-add');
var items = JSON.parse(localStorage.getItem('selected_items')) || {};

for (i = 0; i < addBtn.length; ++i) {
  if (items[addBtn[i].id]) {
    addBtn[i].classList.add('added');
  }
  addBtn[i].addEventListener('click', function() {
    this.classList.toggle('added');
    if (this.classList.contains('added')) {
      items[this.id] = true;
    } else {
      items[this.id] = false;
    }
    localStorage.setItem('selected_items', JSON.stringify(items));
  })
}

View this fiddle link for demonstration https://jsfiddle.net/uwqevc65/

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

Preloading Vue dynamic routes for optimal performance

Currently dealing with a challenge on my Vue project and could use some help. I'm looking to prerender specific dynamic routes when I navigate to a particular route within the application. On the /works route, there's a list of items displa ...

Navigating the elements within R Shiny: A comprehensive guide

Can anyone help me figure out how to access specific elements in my Shiny app using their HTML tags? In this particular example, I need to retrieve all h1 elements along with their respective labels and IDs. library(shiny) ui <- fluidPage( h1("Get" ...

Opening a custom favicon in Google Chrome within a fresh tab using the URL http://localhost/:[port]/

When a user clicks on a button on page A, my JavaScript code opens a new window (page B). Everything seems to be working correctly on page B, except for the fact that the favicon doesn't appear in Chrome (although it shows up fine in Firefox). I have ...

Efficiently Organizing Database Content: Ordering List with Dropdown Menu and Pagination

Is the title of this script clear? Essentially, I developed a PHP script to retrieve data from a database and display it. I then implemented code to use a drop-down menu for sorting that data. Everything was working fine until I attempted to add pagination ...

Using both italic and regular text in an HTML (or ASP.NET) textbox can add emphasis and enhance readability for

Is there a way to achieve this using JavaScript? For instance, if the initial text is 'Axxxxxx', I want it to be displayed in a textbox with normal style for the first letter and italic style for the rest like 'A*xxxxxx*' If the initia ...

Is there a way to dynamically change the helperText of a Material UI TextField using its current value through code?

I'm currently attempting to dynamically change the helperText of a Material UI TextField based on the value entered into the field. Below is my current implementation: const defaultScores = { STR: 10, DEX: 10, CON: 10, INT: 10, WIS: 10, CH ...

"Unleash the power of the Web Audio API by releasing

Currently, I am utilizing the WEB Audio API within a Webapp to render an Audio Signal. However, I have encountered an issue where Chrome's RAM usage gradually increases as it loads an audio file every second. Unfortunately, I am unsure of how to relea ...

Trigger a JavaScript function after Angular has completed its process

Once all data binding is completed and there are no more tasks for the Angular javascript to perform, I need to execute a function that toggles the display of certain divs. Attempted Solutions I want to avoid using timeouts: The timing of Angular's ...

Using web workers to streamline loading objects in Three.js

I need to figure out how to efficiently load and parse a large 3D file using three.js and its associated Loader like PLYLoader. The current issue is that the parsing process takes a significant amount of time, causing the JavaScript-based UI to freeze up. ...

The vital role of Package.json in the distribution of packaged products

I am currently uncertain about the purpose of package.json in relation to packaging. My understanding is that dependencies listed under dependencies will be included in the distribution package, while those under devDependencies will not be included. How ...

Utilizing Ajax to upload various files from separate input sources simultaneously

I want to upload multiple textual/select inputs along with two different file inputs to a PHP file using Ajax. The images from the file inputs are specific and need to be identified by their input names, so I cannot use <input type="file" multiple>. ...

Can the underline height be adjusted when a developer uses `text-decoration: underline;` in CSS to generate an underline effect?

Can the height of the underline created using text-decoration: underline; in CSS be adjusted? I used CSS to apply an underline to the word "about" with an 'id' of '#title4' but I want to increase the space between the word and the unde ...

What is the best way to remove the box-model from an element?

Within my VueJS project, I am faced with nested elements that are generated dynamically like this: <container> <outerElement class="outer" v-for="obj in objects"> <innerElement class="inner" v-for="el ...

CSS Grid having trouble with wrapping elements

Greetings to all, As a newcomer to the world of web development, I am currently exploring the wonders of the CSS grid tool. However, I have encountered a roadblock: My intention is for the cards to automatically flow one by one into the next row while ma ...

Objects being collected as arrays of arrays in garbage collection

I recently came across an article stating that a simple delete is not sufficient to release memory allocated for an object. In my current scenario, I have an Object with several subOjects structured like this: MyObject[idx]['foo']. Is there a me ...

Efficiently transferring input to a Typescript file

Is there a better way to capture user input in Angular and pass it to TypeScript? <form > <input #input type="text" [(ngModel)]="inputColor" (input)="sendInput(input.value)" /> </form> The current method involves creating a ...

Not implementing auto-scroll feature because of the presence of `position: sticky` or `position: fixed` CSS properties

I'm encountering a console warning while working on my Nextjs project. Here is the snippet of my code: <aside className={`site-off desktop-hide ${showMenu ? "show-menu" : ""}`}> .... </aside> And here is the relevant ...

Interactive checkboxes within a classic ASP webpage

I'm encountering an issue while generating checkboxes dynamically on a .asp page. Within a table cell, I am utilizing the following code (note - rsMaint is a recordset): <% if not rsMaint.EOF then rsMaint.moveFirst index = 1 %> ...

What is the best way to submit updated data from an Angular form?

Currently, I have a situation where multiple forms are connected to a backend service for storing data. My query is whether there exists a typical angular method to identify which properties of the model have been altered and only send those in the POST r ...

Sorry, Computed styles are not available in IE 11 Edge DevTools

Currently facing an issue with a component element rendering differently on IE11, however the DevTools for both IE and Edge aren't showing any CSS in the Styles or Computed tab. What is the correct way to debug this situation? Comparison from left to ...