13.2. JavaScript Helpers

For using JavaScript in the view, there are some useful helpers available.

javascript_tag

The easiest way of using JavaScript in a view is via javascript_tag.
With the following line in the view, you can execute an alert when the page is accessed:
<%= javascript_tag "alert('Just an example.')" %>
The HTML code generated is this:
<script type="text/javascript">
//<![CDATA[
alert('Just an example.')
//]]>
</script>

button_to_function

The helper button_to_function creates a button whose onclick handler executes a JavaScript.
Once more the example with the alert. The ERB code in the view looks like this:
<%= button_to_function "trigger alert", "alert('Just an example.')" %>
The generated HTML code:
<input onclick="alert('Just an example.');" type="button" value="trigger alert" />

Thank you for your support and the visibility by linking to this website on Twitter and Facebook. That helps a lot!