0

I have a dropdown menu with anchor links for my page. I want to change the button contents to reflect which anchor it is currently on. To do this I wrote a function that is executed when the button is clicked. It then goes through the array of anchor names and if it matches the array item to the current URL, it updates the button. Like so:

<button onclick="changeURL()">Select Section</button>
function changeURL() {
// function that gets the current url and gets the word after the hash
    var url=window.location.hash;
    console.log(url);
    // loop through array keys and see if hash mashes url
    for (let i=0; i < keys.length; i++) {

      currentURL = "#" + keys[i];
        if (url == currentURL) {
            document.getElementById("dropdownbutton").innerHTML= keys[i];
            break;
        }
    }

}

However, this doesn't work correctly. While the button is being updated, it is only after it is clicked the second time that the function is executed and the URL is matched again. You can see this below (see the URL in the address bar vs the option I choose): enter image description here

This is pretty useless since button needs to reflect the current anchor link, not the one before it. How do I correct my code to reflect the current anchor link? How can I change the innerHTML of the button as soon as the URL changes? Right now it is always one behind the actual one.

2 Answers 2

1

You could use the hashchange event to change the text

const keys = ['a-thing', 'my-dog', 'foo-bar'],
      dBtn = document.getElementById('dropdownbutton'),
      defaultText = ''

window.addEventListener('hashchange', function(e){ 
  const key = keys.find(k => location.hash === '#' + k );
  dBtn.textContent = key ? key : defaultText;
});
<div>
  <button id="dropdownbutton"></button>
  <div><a href="#a-thing">A thing</a></div>
  <div><a href="#my-dog">My Dog</a></div>
  <div><a href="#foo-bar">Foo Bar</a></div>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

This works like magic, thank you so much. I didn't know the hashchange event existed. You have been most helpful :)
0

You could add onclick event for your dropdown-contents and call your function when a content is clicked. Example:

<ul id="dropdownbutton">
    <li><a href="#" onclick="changeURL()"></a></li>
    <li><a href="#" onclick="changeURL()"></a></li>
</ul>

1 Comment

This has the same issue as I need to double click the link before the text changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.