I'm trying to add a live clock onto a webapp that I'm building with Rails and I've found an answer that gives me the JS for the clock. The solution can be found here: How to show current time in JavaScript in the format HH:MM:SS?
I've added the code to my /app/assets/javascripts folder under the title of 'time.js'.
How can I call the method in this script to run/render on my home page (called 'Home.html.erb' in the Views section of my webapp).
Here is the code of the JS Clock Script:
(function () {
function checkTime(i) {
return (i < 10) ? "0" + i : i;
}
function startTime() {
var today = new Date(),
h = checkTime(today.getHours()),
m = checkTime(today.getMinutes()),
s = checkTime(today.getSeconds());
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
})();
And here is the code in my 'home.html.erb' page where I'm trying to render the code:
<div class="col box">
<p><i class="far fa-clock"></i><%= javascript_tag "startTime()" %></p>
</div>
I also have the following under config/initializers/assets.rb:
Rails.application.config.assets.precompile += %w( time.js )
And the following under 'application.html.erb':
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag "time", 'data-turbolinks-track': 'reload' %>
Apologies for the lack of examples/unclear question earlier!
TL;DR is that I'm trying to run the code in 'time.js' inside my 'home.html.erb' file but don't know how to do it.
Regards, Llausa