Reputation: 61
I need to add active class to the links and change active state while navigating page. I have tried with this but changes not applying after switching between links. (not working after page reload)
Here is my code
$('#shortcuts-main > li').click(function (e) {
$(".shortcut-link-active").removeClass("shortcut-link-active");
$(this).addClass("shortcut-link-active");
});
a{
color:black;
padding-bottom:15px;
display:block;
}
.shortcut-link-active a{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="shortcuts-main">
<li>
<a href="#">Link 1</a>
</li>
<li>
<a href="#">Link 2</a>
</li>
<li>
<a href="#">Link 3</a>
</li>
<li>
<a href="#">Link 4</a>
</li>
</ul>
Any ideas?
Upvotes: 0
Views: 162
Reputation: 4782
Modification done to the DOM will not persist after the page is refreshed. A solution for this is to save the data on the client and then read after reloading.
Unfortunately localstorage
won't work on Stackoverflow, but at least you can see some code:
$('#shortcuts-main > li').click(function(e) {
$(".shortcut-link-active").removeClass("shortcut-link-active");
$(this).addClass("shortcut-link-active");
console.log('id:', $(e.target).data('id'))
localStorage.setItem('shortcut-link-active', $(e.target).data('id'));
});
const lastActiveLink = localStorage.getItem('shortcut-link-active');
if (lastActiveLink) {
$('#shortcuts-main')
.find(`[data-id='${lastActiveLink}']`)
.parent()
.addClass('shortcut-link-active')
}
a {
color: black;
padding-bottom: 15px;
display: block;
}
.shortcut-link-active a {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="shortcuts-main">
<li>
<a data-id="link-id-1" href="#">Link 1</a>
</li>
<li>
<a data-id="link-id-2" href="#">Link 2</a>
</li>
<li>
<a data-id="link-id-3" href="#">Link 3</a>
</li>
<li>
<a data-id="link-id-4" href="#">Link 4</a>
</li>
</ul>
Upvotes: 2