0

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

Llausa
  • 39
  • 8
  • Apologies if I'm repeating the question - it may have been answered already but unfortunately I haven't found anything Rails-specific... – Llausa May 09 '19 at 20:00
  • Isn't [this SO answer](https://stackoverflow.com/questions/22937676) rails-specific? `<%= javascript_tag "yourFunction()" %>` – Christian May 09 '19 at 21:19

2 Answers2

1

You can use javascript_include_tag to tell the Asset Pipeline to include the Javascript file in the page

More on the Asset Pipeline and how to use javascript_include_tag here

Benjamin Vogler
  • 336
  • 3
  • 5
0

I'm unsure if this is correct as I am a litte confused but I understand that you are wanting to just run the JS script. Assuming you've included the script in the home.html file then it should work.

Check if you have correctly go to the right files i.e using .../ for going backward in the directory.

Failing this, and without any examples or link to your code, check that you have included the div with an id of time (as per example in link) as this is where it writes the HTML from the JS to.

George
  • 19
  • 9