Search code examples
jquerylaravelcountdown

Countdown in Laravel


I am making a countdown in Laravel with a plugin , I have the following code with javascript

 <script type="text/javascript">
  $('.clock').countdown('2015/05/25', function(event) {
   $(this).html(event.strftime('%D días %H:%M:%S'));
 });
 </script>

This code works correctly but I need to show the diferents finnishes dates in Laravel

@foreach ($products as $subasta)
    {{ $subasta->id }}</p>
    {{ $subasta->name}}</p>
    {{ $subasta->startdate}}</p>
    {{ $subasta->duration}}</p>
    <span class="clock"></span>
@endforeach

How could I pass the date with the item startdate to Javascrip countdown ? Because I recieve the same format in database.


Solution

  • You can use this method:

    http://hilios.github.io/jQuery.countdown/examples/multiple-instances.html

    Html:

    <div data-countdown="2016/01/01"></div>
    <div data-countdown="2017/01/01"></div>
    <div data-countdown="2018/01/01"></div>
    <div data-countdown="2019/01/01"></div>
    

    JS:

    $('[data-countdown]').each(function() {
       var $this = $(this), finalDate = $(this).data('countdown');
       $this.countdown(finalDate, function(event) {
         $this.html(event.strftime('%D days %H:%M:%S'));
       });
    });
    

    So basically you would need to add a data attribute to each of your products SPAN and print the date inside:

    @foreach ($products as $subasta)
        {{ $subasta->id }}</p>
        {{ $subasta->name}}</p>
        {{ $subasta->startdate}}</p>
        {{ $subasta->duration}}</p>
        <span class="clock" data-countdown="{{ $subasta->startdate}}"></span>
    @endforeach
    

    And then update your javascript to loop all the elements and use the attribute as the date. You could use the JS code above and adjust, if you want, the attribute name and variables name or the format text.