Search code examples
javascripthtmljsonleafletcountdown

Insert multiple countdown on the popup of a marker leaflet map


My goal is to show on each popup marker the countdown based on the Json (obj.time). The coountdown has to be showed on the <div id='demo'> If i insert a single countdown for all the <div id='demo'> is working but not with multiple value.

I tried to concatenate the obj[i].id to the id = 'demo' to have multiple id for each countdown like this <div id='demo"+obj[i].id+"'> Then i did the same with the document.getElementById("demo"+obj[i].id).innerHTML = hours + "h "+ minutes + "m " + seconds + "s ";

The Error that i receive is Uncaught TypeError: Cannot read property 'id' of undefined at (index):215

Here is my project https://jsfiddle.net/tiziako/wpo32g6a/


Solution

  • You have to put a new loop in the interval function:

    var x = setInterval(function() {
      for(var i = 0; i < obj.length; i++){
         if(document.getElementById("demo"+obj[i].id)){
            // Get today's date and time
            var now = new Date().getTime();
    
            // Find the distance between now and the count down date
            var distance = new Date(obj[i].time).getTime() - now;
    
            // If the count down is finished, write some text and continue loop
            if (distance < 0) {
                document.getElementById("demo"+obj[i].id).innerHTML = "EXPIRED";
                continue;
            }
            // Time calculations for days, hours, minutes and seconds
            var days = Math.floor(distance / (1000 * 60 * 60 * 24));
            var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
            // Display the result in the element with id="demo"
            document.getElementById("demo"+obj[i].id).innerHTML = hours + "h "+ minutes + "m " + seconds + "s ";
    
          }
        }
    }, 200);
    

    Also you can set the interval faster, then it will show the timer faster, if you open a popup.

    https://jsfiddle.net/falkedesign/7fkpvzta/