How to Call a JavaScript Function from an HTML.Erb

Ruby on rails Call javascript Function

There is a workaround, though.
In Rails 6 you can change the function signatures from:

function myFunction() { ... }

to:

window.myFunction = function() { ... }

So according to your code try this :-

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

window.greatTutorial = function() {
alert('Rails Guides are the best');
}

How to call js functions defined in script tag of the erb file?

Give your paragraph a class like so:

<p class="p_class"></p>

then put this

<script>
document.getElementsByClassName('p_class')[0].textContent = sayHello();
</script>

at the bottom of your app/views/invoices/pdf.html.erb partial.

Call a javascript function from ruby on rails view

Your js function is not good:

  • First you try to call the countdown inside itself
  • Then, for a countdown, you should use setInterval instead of setTimeout (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"



Related Topics



Leave a reply



Submit