javascripthyperlinkvisited

Is it possible to determine which links on the site have been clicked by the user and which have not yet been placed by the user?


There is a list of links, I need to track which of them have already been clicked, and which have not been clicked yet.

For example: There are no links that have been clicked, I should start with the first one. The first and second links have been placed, you should start with the third.

How can this be implemented?

Was looking to find a solution using querySelector and a:visited, but the browser won't let me access that information.

replit


Solution

  • Here is a localStorage version.

    On your server, remove ['https://www.youtube.com/']; // including the comment slashes

    Also remove the e.preventDefault() I put to check the link gets highlighted

    // on your server remove the test "['https://www.youtube.com/']; //" below - localStorage is not supported in snippets
    const visitedList = ['https://www.youtube.com/']; // JSON.parse(localStorage.getItem('visited') || '[]');
    window.addEventListener('DOMContentLoaded', () => {
      const container = document.querySelector('.cont');
      const links = container.querySelectorAll('.link');
      const setVisit = (href) => {
        if (href && !visitedList.includes(href)) visitedList.push(href);
        links.forEach(link => {
          if (visitedList.includes(link.href)) link.classList.add('visited');
        });
      };
      container.addEventListener('click', (e) => { e.preventDefault(); // comment this out after testing
        const tgt = e.target.closest('a.link');
        if (!tgt) return; // not a link
        setVisit(tgt.href);
      });
      setVisit();
    });
    li {
      padding: 20px;
    }
    
    .link {
      color: #a955ff;
      text-decoration: none;
    }
    
    .link.visited {
      /* changed from .link:visited to manage ourselves */
      color: #ff5b55;
    }
    <div class="cont">
      <ul>
        <li><a class="link" href="https://github.com/">Github</a></li>
        <li><a class="link" href="https://www.netflix.com/">Netflix</a></li>
        <li><a class="link" href="https://www.youtube.com/">Youtube</a></li>
        <li><a class="link" href="https://dribbble.com/">Dribbble</a></li>
      </ul>
    </div>