I am trying to reuse the output of the year variable. I will need to reuse the updated value [based on hashchange] in multiple functions later on. It displays the correct value in the browser console, but it doesn't display in the browser.
<html>
<body>
<p></p>
<a href="#2018-01">1</a>
<a href="#2018-02">2</a>
</body>
<script>
location.hash = '#2019';
showHash();
var p = document.querySelector('p');
p.innerHTML = window.year;
function showHash() {
return year = location.hash;
}
window.onhashchange = showHash;
</script>
</html>
By assigning
location.hashtoyearyou are not modifyingp.innerHTML.yearandp.innerHTMLare not referencing each other's value. When you initialised as follows:The value of
yearwas copied so now you have two values which happen to be the same at that moment, but they are not linked so that if you would assign a new value to the one, it would also update the other. No, they are not references.So in the event handler you should also assign the new hash to
p.innerHTML, or better -- as the hash is text -- assign it top.textContent: