How do I call a JavaScript function from html.erb
in application.js
function displayClock() {
var digital = new Date();
var hours = digital.getHours();
var minutes = digital.getMinutes();
var seconds = digital.getSeconds();
var amOrPm = 'AM';
if (hours > 11) amOrPm = 'PM';
if (hours > 12) hours = hours - 12;
if (hours == 0) hours = 12;
if (minutes <= 9) minutes = '0' + minutes;
if (seconds <= 9) seconds = '0' + seconds;
dispTime = '<b>'+hours + ':' + minutes + ':' + seconds + ' ' + amOrPm+'</b>';
document.getElementById('time').innerHTML = dispTime;
setTimeout('displayClock()', 1000);
}
and in home.html.erb
displayClock();
but it's not calling function!
To include our JavaScript file in the HTML document, we have to use the script tag <script type = "text/javascript" src = "function.
The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.
No, you can't trigger JavaScript from CSS directly. What you can do is use CSS selectors to find the elements you want to watch in this way, and then watch for mouse events.
Create the js. erb in the view folder itself with the same name as that of the action. In the view where some form is created which will be calling this action, make the request using :remote => true .
You probably need to use proper tag to indicate that you're writing JS code:
<script type="text/javascript">
displayClock();
</script>
Plus, since you probably use jQuery (it's default in Rails), you may want to make sure the function is called after whole document is loaded:
<script type="text/javascript">
$(document).load(function(){
displayClock();
});
</script>
I'd also advice you not to write your JS in application.js
and use this file only as a manifest file, which includes your other scripts through Rails asset pipeline.
Also you can take advantage of the javascript helper javascript_tag in your html.erb
file
<%= javascript_tag "displayClock()" %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With