Javascript: Update inner html when URL changes

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;
    // 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];


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.


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;
  <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>