Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a JavaScript function from an html.erb

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!

like image 618
Iziksh Avatar asked Apr 08 '14 12:04

Iziksh


People also ask

How do you reference a JavaScript function in HTML?

To include our JavaScript file in the HTML document, we have to use the script tag <script type = "text/javascript" src = "function.

How do you call my function in JavaScript?

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.

Can we call JavaScript function from CSS?

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.

Where do I put JavaScript ERB files?

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 .


1 Answers

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()" %>
like image 147
Marek Lipka Avatar answered Nov 05 '22 00:11

Marek Lipka