Search code examples
javascriptphpcountdown

Countdown in hrs/minutes/seconds in php function using javascript


I have tried alot of things but i don't know really much about javascript. I have a countdown script but it only countdown in seconds but i need hours minutes and seconds.

This is the code:

function countDown($i, $verschil){

$msg = "

<script type='text/javascript'>
     var seconds". $i."=". $verschil.";
     function display". $i."()
     {
       seconds". $i."=seconds". $i."-1;
       if(seconds". $i."<0)
       {
          countdown". $i.".innerHTML=\"0\";
       }
        else
        {
           var countdown". $i." = document.all? document.all[\"cd".$i."\"] : document.getElementById ? document.getElementById (\"cd". $i."\")
           : \"\";
           if (countdown". $i.")
          {
            countdown". $i.".innerHTML=seconds". $i.";
            setTimeout('display". $i."()',1000);
          }
       }
     }
    display". $i."();
  </script>

";

return $msg;

}
  • $i = name of countdown, $verschil = Seconds to countdown

I hope someone can help me, tried things for almost 20 hours but i can't get this working.


Solution

  • You could try this.. I just wrote it without chekcing it.. No Promis this works

    function countDown($name, $time){
    
    $seconds = gmdate("G", $time);
    $minutes = gmdate("i", $time);
    $hours   = gmdate("s", $time);
    
    $msg = "
    
    <script type='text/javascript'>
         var seconds".$name."=".$seconds."
         var minutes".$name."=".$minutes."
         var hours".$name."=".$hours."
         function display". $name."()
         {
            if(hours".$name." != 0 && minutes".$name." != 0 && seconds".$name." != 0) {
                if(seconds".$name." > 0) {
                    seconds".$name." = seconds".$name."-1;
                } else {
                    if(minutes".$name." > 0) {
                        minutes".$name." = minutes".$name."-1;
                    } else {
                        hours".$name."= hours".$name."-1;
                    }
                }
    
                var countdown".$name." = document.all? document.all[\"cd".$name."\"] : document.getElementById ? document.getElementById (\"cd". $name."\")
               : \"\";
               if (countdown". $name.")
              {
                countdown". $name.".innerHTML= ''+hours".$name."+':'+minutes".$name."+':'+seconds".$name.";
                setTimeout('display". $name."()',1000);
              }
    
            } else {
                countdown". $name.".innerHTML=\"0:0:0\";
            }
         }
        display". $name."();
      </script>
    
    ";
    
    return $msg;
    
    }
    

    Note: This mixed style is a bad codig style... for testing ok but you should try to avoid it