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 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"
Related Topics
How to Count Duplicates Hash Itens in Ruby 1.8.5 ( Sketchup Ruby API )
Flatten a Ruby Array Without Using Built-In 'Flatten' Method
How to Create an Association Between Two Rails Models
Sublime Text Can't Understand Gets.Chomp
How to Handle Combination []+= for Auto-Vivifying Hash in Ruby
Rational - Original Numbers in Ruby
Ruby File Reading Parallelisim
Inserting an Array into Every Nth Element of Another
Undefined Method 'Email' for Nil:Nilclass in Exibe the Mail of Table Father
Regular Expression to Match Only the First File in a Rar File Set
Testing HTML5 File Upload with Capybara/Selenium Webdriver - Ruby
How to Build a Docker Image for a Ruby Project Without Build Tools
Errno::Enoent No Such File or Directory Rails 4
Ruby: Length of a Line of a File in Bytes
"Bad Ecpoint" Ssl Error on Fresh Rvm Ruby 1.9.3 Install on Osx Mountain Lion