Youtube channel !

Be sure to visit my youtube channel

Monday, July 15, 2013

Mark visited links using JavaScript and localStorage

The following code will analyze each and every link on your webpage in a way so when a user clicks on a link it will store its location in browser's localStorage. The code first loops over the links, placing event handlers on their click event. Then when a user clicks on a link it checks for its existence in the local-storage array and if not pushes it there. At the same time adds the class 'visited' to all visited links found in the array.
If you would like to understand more of its internal functionality, I would suggest taking a look at the comprehensive course: JavaScript for beginners - learn by doing

function check_visited_links(){
var visited_links = JSON.parse(localStorage.getItem('visited_links')) || [];
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
    var that = links[i];
    that.onclick = function () {
        var clicked_url = this.href;
        if (visited_links.indexOf(clicked_url)==-1) {
            visited_links.push(clicked_url);
            localStorage.setItem('visited_links', JSON.stringify(visited_links));
        }
    }
    if (visited_links.indexOf(that.href)!== -1) { 
        that.parentNode.className += ' visited';
    }
}
}

if you want to add some styling just add the following CSS rule:

.visited{
color:silver
}

Subscribe To My Channel for updates

Integrating AI code helpers into Visual Studio Code

In this guide, we’ll walk through setting up a local AI-powered coding assistant within Visual Studio Code (VS Code). By leveraging tools s...