Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The value that I get from <li> doesn't change when the href is changed

I have a ul li in html that is a dropdown.

Index.html

<ul class="dropdown-menu" style="width: 100%;">
  <li rel="3" class="category"><a class="dropdown-item" href="/index2.html#section2" target="_blank"></a></li>
  <li rel="4" class="category"><a class="dropdown-item" href="/index2.html#section2" target="_blank"></a></li>
  <li rel="5" class="category">
    <a class="dropdown-item" href="/index2.html#section2" target="_blank"></a> 
  </li>
</ul>

script.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var val = 1;
$(".category").click(function(){
    val = $(this).attr('rel');
  });

In my index.html when I checked the console, the val is already changed to whatever the user clicked, but when it opened the index2.html, the val is back again to 1. How can I solve it?

>Solution :

The issue is that the val variable isn’t persisting throughout reloads and on other pages on the site. This is something that regular old variable just can’t do.

A common solution to this is to put state like val in localStorage. Properties of localStorage persist through page reloads and can be accessed on any page of your site. Instead of using traditional variables, you use the localStorage.setItem() and localStorage.getItem() functions.

To use localStorage with your code, you’d just need to change your JS setting val to this:

localStorage.setItem('val', 1);
$(".category").click(function(){
    localStorage.setItem('val', $(this).attr('rel'));
});

Then whenever you need to access the val variable you just use this instead:

localStorage.getItem('val')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading