So I've just create a little vanilla Javascript snippet for this one. It saves the href
attribute in an array, which than is saved as JSON in localStorage. You could extend/edit it anyway - it is pretty easy coded - I will use it maybe also in 1 or 2 side projects.
HTML:
<h1>Repo services</h1>
<ul>
<li><a class="trackVisit" href="https://github.com">GitHub</a></li>
<li><a class="trackVisit" href="https://gitlab.com/explore">GitLab</a></li>
<li><a class="trackVisit" href="https://www.codeplex.com/">CodePlex</a></li>
<li><a class="trackVisit" href="https://bitbucket.org/">Bitbucket</a></li>
</ul>
<button>Reset</button>
All links that should be tracked/saved/remembered will have the class trackVisit
. So not all links on the page will be styled this way.
Now this little script will work with localStorage
:
// helper function
var forEach = function(array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
// init
if (localStorage.getItem('visitedLinks') === null) {
localStorage.setItem('visitedLinks', JSON.stringify([]));
}
// get already visited links
function getVisitedLinks() {
return JSON.parse(localStorage.getItem('visitedLinks'));
}
// save visits
forEach(document.querySelectorAll('a.trackVisit'), function(index, element) {
element.addEventListener('click', function saveVisit() {
var visitedLinks = getVisitedLinks();
if (visitedLinks.indexOf(element.getAttribute('href')) === -1) {
visitedLinks.push(element.getAttribute('href'));
}
localStorage.setItem('visitedLinks', JSON.stringify(visitedLinks));
refreshVisits(visitedLinks);
});
});
// style the links
function refreshVisits(visitedLinks) {
forEach(document.querySelectorAll('a'), function(index, link) {
link.classList.remove('visited');
});
visitedLinks.forEach(function(el, key) {
if (document.querySelector('a[href="' + el + '"]') !== null) {
document.querySelector('a[href="' + el + '"]').classList.add('visited');
}
});
}
// run it!
refreshVisits(getVisitedLinks());
// reset visits button
document.querySelector('button').addEventListener('click', function() {
localStorage.setItem('visitedLinks', JSON.stringify([]));
refreshVisits(getVisitedLinks());
});
And add a bit of style to visited links:
a.visited {
position: relative;
color: #ccc;
text-decoration: line-through;
padding-left: 15px;
}
a.visited:before {
content: "\2713 ";
position: absolute;
left: 0;
top: -2px;
}
Now a demo can be also found at CodePen. I think with jQuery it would be cleaner but we don't need jQuery!