7

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!

Alok Anand
  • 3,346
  • 1
  • 20
  • 17
Iziksh
  • 119
  • 1
  • 1
  • 8

1 Answers1

26

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()" %>
mmsilviu
  • 1,211
  • 15
  • 25
Marek Lipka
  • 50,622
  • 7
  • 87
  • 91