Why is output being duplicated inside hashchange event listener?

68 Views Asked by At

I've generated the months of the year with a hash of #2019-01 #2019-02 etc.. Every time I click on a link it appends another list of the months.

It's only supposed to display one copy of the month links but output the updated hash. So if I click on February it should output #2019-02.

https://jsfiddle.net/captlid/gkhe4naz/3/

var date = new Date();
location.hash = date.getFullYear();
var p = document.querySelector('p');
p.innerHTML = location.hash;

window.addEventListener('hashchange', function() {

   for (dz = 0; dz < 12; dz++) { 
      p.innerHTML += '<a href="'+location.hash+'-'+String("0"+(dz+1)).slice(-2)+'">'+ months[dz] +'</a>&nbsp;';
   }
   p.innerHTML += location.hash; 
});
1

There are 1 best solutions below

1
jmcgriz On

Your code is working properly as it's written. I think you accidentally have your calendar output code inside of your hashchange function. If you move it outside, it should work as you expect. Also, you're building your calendar inside of your p element instead of the calendar element. the code below shows a functioning version

var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var calendar = document.querySelector('#calendar');
var date = new Date();
location.hash = date.getFullYear();
var p = document.querySelector('p');
p.innerHTML = location.hash;

for (dz = 0; dz < 12; dz++) {
    calendar.innerHTML += '<a href="' + location.hash + '-' + String("0" + (dz + 1)).slice(-2) + '">' + months[dz] + '</a>&nbsp;';
  }

window.addEventListener('hashchange', function() {


  p.innerHTML = location.hash;
});
<div id="calendar"></div>
<p></p>