checking the current url and then marking a link active based on that url

i want a script that can check the current page uri and then match it to a list of links to be able to add an active class that survives page reloading

So here we go...

1. Get the current page url.

Using this example. get the current url in javascript

2. Get all the nav elements

Need to load all the nav elements into an array and then check if they have the current url

 

HTML

<div class='test-nav'>
<ul class="test-nav-ul" id="test-nav-ul">
<li class="testnavlink"><a href="https://kruxor.com/view/content/MrXNv/kruxor-moving-from-bootstrap-to-css-grid/">Link One</a></li>
<li class="testnavlink"><a href="https://kruxor.com/view/code/lWhoL/badge-border-colour-is-too-dark-or-light-on-number-badges-fixed/">Link Two</a></li>
<li class="testnavlink"><a href="https://kruxor.com/view/code/L8XP1/">Link Three (alternate link for this page)</a></li>
<li class="testnavlink"><a href="https://kruxor.com/view/code/L8XP1/checking-the-current-url-and-then-marking-a-link-active-based-on-that-url/">checking the current url and then marking a link active based on that url</a></li>
<li class="testnavlink"><a href="https://kruxor.com/view/code/WSQr2/using-gzdeflate-on-a-string-php/">Link Four</a></li>
</ul>
</div>

CSS

.testnavlink .active {
  font-weight:bold;
  color:#F00;
}

Javascript

window.onload = function() { 
    var all_links = document.getElementById("test-nav-ul").getElementsByTagName("a"),
        i=0, len=all_links.length,
        full_path = location.href.split('#')[0]; //Ignore hashes?

    // Loop through each link.
    for(; i<len; i++) {
        if(all_links[i].href.split("#")[0] == full_path) {
            all_links[i].className += " active";
        }
    }
}

Other Items in javascript
Page Views

This page has been viewed 51 times.

Search Code
Search Code by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code snippits here, mostly for my reference. Also if i find a good site, i usually add it here.

âĪðŸ‘Đ‍ðŸ’ŧðŸ•đ

Random Quote
For a long time it had seemed to me that life was about to begin - real life. But there was always some obstacle in the way, something to be gotten through first, some unfinished business, time still to be served, or a debt to be paid. Then life would begin. At last it dawned on me that these obstacles were my life.
Alfred D. Souza