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
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')