Search code examples
javascriptjqueryruby-on-railsruby-on-rails-5flipclock

How to make a countdown in ruby on rails with flipclock.js?


I am trying to make a countdown for an offer which ends on July 15, 2016.

I was able to add flipclock to my app but I couldn't figure our how to send the remaining time to the javascript.

Can anyone kindly help?

Here is the code. Thanks.

EDIT

Sorry I forgot to mention the timezone.
One offer is at July 15, 2016 GMT
Another offer is at July 25, 2016 EST.

This is my app's timezone on heroku.

suai@railrial:~/workspace/conrse (master) $ rails c
Loading development environment (Rails 5.0.0.rc2)
>> Time.zone.name
=> "UTC"
>> 

<!DOCTYPE html>
<html lang="en">

<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flipclock/0.7.8/flipclock.min.css">
</head>

<body>

  <div class="clock"></div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/flipclock/0.7.8/flipclock.min.js"></script>

  <script type="text/javascript">
    var clock = $('.clock').FlipClock(25 * 25 * 35 * 35, {
      clockFace: 'DailyCounter',
      countdown: true,
    });
  </script>

</body>

</html>


Solution

  • So I'm assuming you have offer end date as a DateTime in your database.

    Lets say the value is in offer_ends attribute of your @item object

    <script type="text/javascript">
      // We need to convert the time difference to integer
      time_diff = <%= (@item.offer_ends - Time.now).to_i.abs %>;
      //Rails will put the seconds difference right there, so if you inspect your code will look like this in browser
      //time_diff = 1035937;
    
      var clock = $('.clock').FlipClock(time_diff, {
        clockFace: 'DailyCounter',
        countdown: true,
      });
    </script>
    

    Hope this helps