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!
CodePudding user response:
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.
CodePudding user response:
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.
CodePudding user response:
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
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.