简体   繁体   中英

Call a javascript function from ruby on rails view

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?

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM