There has been some discussion of how it is possible to convert a Rails UTC DateTime into a Javascript date value, like here. However, I am seeing errors when I try to go a step further and make that DateTime dynamic.
In the end, I am trying to make a JS countdown timer that will show the remaining seconds between Time.now
(Rails) and a set UTC time called game_start
. I am using this scrappy method for passing a Rails object (like a DateTime from a table) into Javascript.
So currently, I am doing the following:
// This is the scrappy way I am storing a temp value for DateTime
<%= content_tag :div, class: "temp_information", data: {temp: @tempquiz} do %>
<% end %>
<div id="timer"></div>
<script>
$(document).ready(function() {
var dt = $('.temp_information').data('temp');
alert(dt);
});
This returns a UTC string as an alert, like 2016-02-18T23:07:00.000-08:00
. So I am successfully passing that Rails data into JS. T
he issue is when I try to combine it with some Javascript, like:
$(document).ready(function() {
var data = $('.temp_information').data('temp');
var dt = new Date (<%= data.ToJavaScriptMilliseconds() %>);
alert(dt);
});
If I am going to make a timer that counts down, I am going to need to capture the game_start
time (temp is doing that) and convert it to JS Milliseconds (that is breaking). However, when I do that (code is based on this answer), I get this error:
undefined local variable or method `data'
I don't get it at all, since I am defining data
in the line before within the $(document).ready
as the UTC string we saw in the alert. If it knows what data
is and can return the alert in the first instance, how is it unable to produce it in the second instance?