Good morning who is reading this message!
I'm still relatively new to programming and I have a question... I made a Navigation bar: body > div > nav > div > ul > li*10
I have the movement done in CSS
//Barra de Navegacion
const list = document.querySelectorAll('.list');
function activeLink(){
list.forEach((item)=>
item.classList.remove('active'));
this.classList.add('active');
if(list.classlist.contains('active')){
localStorage.setItem('on','true');
} else{
localStorage.setItem('on','false');
}
};
if (localStorage.getItem('on') === 'true'){
list.classList.add('active');
} else {
list.classList.remove('active');
};
list.forEach((item)=>
item.addEventListener('click',activeLink));
The problem is that when I refresh the page or go to another part of it, it does not save the changes. how could i do it with localstorage?
I tried several ways and I can't find the way to do it
Thank you very much in advance!
I think this code is too far down.
if (localStorage.getItem('on') === 'true'){
list.classList.add('active');
} else {
list.classList.remove('active');
};
You should set this set immediatly when the page loads, immediatly after
const list = document.querySelectorAll('.list');
So the list has the correct class from the beginning.
I doubt that using localStorage is the right way to achieve what you want to do. I suggest that each page should have its link highlighted when you open it. This can be achieved by adding classes manually to the link of each page, keeping in my mind it wouldn't be that many links in the navigation.
Not sure what you are trying to achieve with this part of the code, but the syntax you are using is correct. Here is some example of usage of the local storage API to repeat.
You can save key-value pair to the local storage using the syntax:
localStorage.setItem('key', 'value');
You can retrieve the saved value with the following syntax:
localStorage.getItem('key');
If you still can't get the code to work correctly you can try to open your browser's developer tools and look at the storage. If your developer's tools are saying that there are no entries saved to the local storage you then know that the main problem is with saving the key-value pair.
Here's how to open the developer tools in Chrome:
If you still cannot get the code working you should check your browser settings to make sure there are no security settings enabled that are preventing your application from saving to the local storage.