Select active button based on url initially

scripts
#1

I have a sidenav that “reloads” every time, so this will not work:
https://jsfiddle.net/ju39e6fd/5/

The solution must be based on url (I think). I have found this code that I think should do the trick.

<div id="nav">
   <a href=”/about”><button class="btn active">About</a>
   <a href=”/contact”><button class="btn">Contact</button></a>
   <a href="/forum"><button class="btn">Forum</button></a>
</div>

<script>
  (function() {
    alert(window.location.pathname.split('/')[1]) (the slash is removed)
    var nav = document.getElementById('nav'),
    anchor = nav.getElementsByclass('btn'),
    current = window.location.pathname.split('/')[1];

    for (var i = 0; i < anchor.length; i++) {
    if(anchor[i].href == current) {
        anchor[i].className = "active";
    }
   }
 })();
</script>

But there is 2 problem:

  1. The “window.location.pathname.split(’/’)[1]” gives “about” but I need “/about”.
  2. I want to load this javascript when opening the url. What is the syntax for this?.

How do I do this? Thank you for any advice or input on this. Vanilla please.

#2

Hi @sibertius, if each subpage is getting loaded completely anyway your best bet would be to set the active class on the server side… but to answer your questions,

Then you might either add the slash again, or strip the slash from the href you’re comparing it with, or use a regular expression or indexOf() to check if the current URL contains “about”…

There is no special syntax, just include it at the end of your page right before the closing </body> tag.

#3
var anchor = 

var current =

Otherwise this variables will be global for all document JS.

Better if JS packed in external script.

For code execution by document cpening used…

window.addEventListener(
          'load',
          function() {...}
);
1 Like