How can I update javascript/ruby variable automatically (everyday)?

$(document).ready(function(e) {
  $('#countdown').countdown({
    until: date,
    format: 'HMS',
    labels: ['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes', 'Seconds'],
    labels1: ['Year', 'Month', 'Week', 'Day', 'Hour', 'Minute', 'Second'],
    onExpiry: function() {
      $('#countdown').hide();
      $('.reset-button').show();
    }
  });
});

I would like to have the variable ‘date’ to be updated (on click, by time, etc). How can I do that?

This is a application.js.erb file. Which means JS and Ruby variables are both welcomed.

Answer

var date, year, month, day

$(document).ready(function(e) {
  date = new Date();

  if (date.getHours() > 22) {
    date.setDate(date.getDate()+1)
  }

  year = date.getFullYear();
  month = date.getMonth();
  day = date.getDate();

  $('#countdown').countdown({
    until: new Date(year, month, day, 22, 00, 00),
    format: 'HMS',
    labels: ['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes', 'Seconds'],
    labels1: ['Year', 'Month', 'Week', 'Day', 'Hour', 'Minute', 'Second'],
    onExpiry: function() {
      $('#countdown').hide();
      $('.reset-button').show();
    }
  });
});

I have found the solution. Notice here that you HAVE TO use JavaScript variables for times. If you use Ruby, then it would not refresh when browser refreshes because the variables are from the server (cache).

Leave a Reply

Your email address will not be published. Required fields are marked *