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

Burnout or toxic culture ?

Outsourcing companies are hell to be in for an experienced programmer, because managers are being allowed to mistakes, which are covered, th...