/    Sign up×
Community /Pin to ProfileBookmark

Select active button from url on load

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.

    to post a comment
    JavaScript

    11 Comments(s)

    Copy linkTweet thisAlerts:
    @SempervivumJun 11.2019 — Not shure, if I understand this correctly: You have the same nav on each page and you want to set the class "active" for that entry that corresponds to the page currently loaded?
    Copy linkTweet thisAlerts:
    @sibertauthorJun 11.2019 — > @Sempervivum#1604523 Not shure, if I understand this correctly: You have the same nav on each page and you want to set the class "active" for that entry that corresponds to the page currently loaded?

    Well, yes and no. I am using Go and templates. Go acts both as web-server (replacing Apache) and "micro framework" sort of. This means that there is only ONE sidenav, but reused on many pages. A dummy site is here:

    http://94.237.25.207:7070/fonts

    As I interpret it, the sidenav (sub_about) is reloaded to its initial status each time. Which means that the click on the sidenav button will be overwritten.

    <div class="container">
    <div class="submenu">
    {{template "sub_about"}} <----- <div id="nav"> as above
    </div>
    <div class="content">
    Content stuff...
    </div>
    </div>


    So, my guess I have to reset the "selected" button att page load. Correct me if I am wrong.
    Copy linkTweet thisAlerts:
    @SempervivumJun 11.2019 — Try this javascript:
    &lt;script&gt;
    (function () {
    var anchors = document.querySelectorAll('#nav a'),
    current = window.location.href;

    <i> </i> for (var i = 0; i &lt; anchors.length; i++) {
    <i> </i> if (current.indexOf(anchors[i].href) != -1) {
    <i> </i> anchors[i].firstElementChild.classList.add("active");
    <i> </i> }
    <i> </i> }
    <i> </i> })();
    <i> </i>&lt;/script&gt;
    Copy linkTweet thisAlerts:
    @sibertauthorJun 15.2019 — @Sempervivum#1604569

    Yes, this script works. Thank You!

    But (as always) when opening this FIRST time it does not select anything. I e the initial selection.

    I guess(!) this can be solved in two ways:

  • 1. This script should not be run at "load". It should be run when "loaded". Is there any way to delay the script until all is loaded?

  • 2. Hardcode the first select by class="btn active" and then remove the "active" part in the script.


  • Any tip how to do this?
    Copy linkTweet thisAlerts:
    @SempervivumJun 15.2019 — Try to place the script at the bottom before the closing </body>
    Copy linkTweet thisAlerts:
    @sibertauthorJun 15.2019 — @Sempervivum#1604769

    The script is already there. More tip?

    EDIT: added an alert and the script works, but as the sidemenu {{template "sub_about"}} is a sub template, it seems not to be loaded simultaneously. My guess.

    Why does this not work?

    (function() {
    var anchors = document.querySelectorAll('#nav a'),
    current = window.location.href;
    for (var i = 0; i < anchors.length; i++) {
    if (current.indexOf(anchors[i].href) != -1) {
    anchors[i].firstElementChild.classList.add("active");
    else
    anchors[i].firstElementChild.classList.add("");
    }
    }
    })()
    Copy linkTweet thisAlerts:
    @SempervivumJun 15.2019 — Is there any way to delay the script until all is loaded?[/quote]Yes, this is possible, although it's not the cleanest way. Try setTimeout:
    (function() {
    setTimeout(function() {
    var anchors = document.querySelectorAll('#nav a'),
    current = window.location.href;
    for (var i = 0; i &lt; anchors.length; i++) {
    if (current.indexOf(anchors[i].href) != -1) {
    anchors[i].firstElementChild.classList.add("active");
    } else {
    anchors[i].firstElementChild.classList.add(""); <br/>
    }
    }
    }, 100);
    })()
    If this does not work, it would be best if you updated your demo so that one can see it in action.
    Copy linkTweet thisAlerts:
    @sibertauthorJun 15.2019 — > @Sempervivum#1604569 Try this javascript:

    Your code works perfect! It was brain malfunction on my side.

    Thank You indeed!
    Copy linkTweet thisAlerts:
    @sibertauthorJul 10.2019 — > @Sempervivum#1604569 Try this javascript:

    This code works perfect https://jsfiddle.net/sofudLz7/3/

    BUT I get errors when validating the html:

    > " The element button must not appear as a descendant of the a element."

    So I have rewritten the html from

    > <a href="/about"><button class="navbtn">About</button></a>

    To omit the button:

    > <a href="/about" class="navbtn">About</a>

    Of course this breaks the Javascript. https://jsfiddle.net/sofudLz7/2/

    Any tip how to get the script to work again?
    Copy linkTweet thisAlerts:
    @SempervivumJul 10.2019 — I didn't test it but it should work if you simply omit the `firstElementChild`:

    https://jsfiddle.net/Sempervivum/6a1z49gx/1/
    Copy linkTweet thisAlerts:
    @sibertauthorJul 10.2019 — > @Sempervivum#1606128 I didn't test it but it should work if you simply omit the

    Of course it works. Thank you indeed!
    ×

    Success!

    Help @sibert spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.20,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...