0

I've been searching but I couldn't find anything that helps me.

I have a file countdown.js app/assets/javascript/countdown.js

// Total seconds to wait
var seconds = 11;

function countdown() {
    seconds = seconds - 1;
    if (seconds < 0) {
        // Chnage your redirection link here
        seconds = 11;
        window.setTimeout("countdown()", 1000);
    } else {
        // Update remaining seconds
        document.getElementById("countdown").innerHTML = seconds;
        // Count down using javascript
        window.setTimeout("countdown()", 1000);
    }
}

// Run countdown function
countdown();

And I want to call this function on my index.html.erb file. What should I do?

1
  • Did you link your js file to your application? add in <script src="countdown.js"></script> if that does not work make sure you specify the correct path Commented May 29, 2018 at 22:37

1 Answer 1

1

Your js function is not good:

So you can do something more like this:

//assets/javascript/countdown.js

function countdown() {
  var seconds = 11
  setInterval(function() {
    if (seconds < 1) {
      seconds = 11
    }
    seconds -= 1
    document.getElementById("countdown").innerHTML = seconds + " seconds"
  }, 1000);
}

window.onload = function() {
  countdown();
};

Be sure your js file is require in your assets/javascript/application.js:

//= require countdown
// OR
//= require_tree .

and your application.js is linked in your layout:

#layouts/application.html.erb
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

Now you can display your countdown in your index.html.erb on a div with id="countdown"

Sign up to request clarification or add additional context in comments.

3 Comments

Can I ask a new question? I want to get this "second" on my div and save in my controller. How can I do it?
I don't really see what you mean by "second". If you want to pass view data to your controller you need params or much more complex js with ajax. Maybe ask another question for that with some code examples.
What I meant is when I click a button get the actual value of my countdown, it has been shown on my DIV, and save this value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.