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!

1
  • On which event you want to call it? And use <script/> tag to enclose your function. Commented Apr 8, 2014 at 12:55

1 Answer 1

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()" %>
Sign up to request clarification or add additional context in comments.

1 Comment

@user3459701 did you try my answer? Did it help?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.