0

How can I add a class to a div when I visit a page in my website and save this on cache?

For example: I have a index.html that looks like this: https://i.stack.imgur.com/6iJEr.png

What I wanna do is when someone click in one div (witch is linked to a page like page3.hml) this div will add a class and save in cache, so when back to index.html this div will still have this class. Like this: https://i.stack.imgur.com/lMjZG.png

The class wold be something like

.visited{
border-bottom: 10px solid red;
}

Is this possible? Sorry for my English :(

  • 2
    Does this answer your question? [Persist variables between page loads](https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads) –  Sep 10 '20 at 22:13

2 Answers2

0

The simplest method would be using the CSS :visited selector if you won't mind converting those divs into hyperlinks.

Then it would be something like:

a:visited {
    border-bottom: 10px solid red;
}

Check out the w3schools article about the hyperlink selectors:

https://www.w3schools.com/css/css_link.asp

Sayed
  • 601
  • 6
  • 21
0

You can use local storage to save the divs. With my example, each div needs a different ID and a click handler added to a class.

SO Snippets doesn't allow local storage so here is a working fiddle: https://jsfiddle.net/hdo4sq9j/2/

    .visited{
        border-bottom: 10px solid red;
    }
    
    <div id="id1" class="clickme">1</div>
    <div id="id2" class="clickme">2</div>
    <div id="id3" class="clickme">3</div>
    
visited = localStorage.getItem('visited')

if (visited === null) {
  localStorage.setItem('visited', []);
  visited = [];
}
else{
    visited = visited.split(",")
}
    
    divs = document.querySelectorAll(".clickme");
    
    divs.forEach(function(div) {
      div.addEventListener("click", function(ev) {
        if (visited.indexOf(div.id) == -1) {
          visited.push(ev.target.id)
        }
        localStorage.setItem('visited', visited);
      })

      if (visited.indexOf(div.id) > -1) {
        div.classList.add("visited")
      }
    });
imvain2
  • 15,480
  • 1
  • 16
  • 21