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?
asked May 29, 2018 at 22:27
Bruno Lopes Bacelar
1252 gold badges2 silver badges15 bronze badges
1 Answer 1
Your js function is not good:
- First you try to call the
countdowninside itself - Then, for a countdown, you should use
setIntervalinstead ofsetTimeout(source here in the "Definition and Usage" section)
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"
answered May 29, 2018 at 23:38
Sovalina
5,6094 gold badges25 silver badges41 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Bruno Lopes Bacelar
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?
Sovalina
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.
Bruno Lopes Bacelar
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.
lang-js
<script src="countdown.js"></script>if that does not work make sure you specify the correct path