Add a JavaScript asset to a Rails application
Completed project: rails_helloworld, the javascript branch
In the previous tutorial, we created a simple Rails application with a view containing only static text. In this guide, we'll add a button to the web page and handle the button click on the client side using a JavaScript asset.
Before starting this tutorial, repeat steps from the previous one to create the basic Rails application. This application references the Webpacker gem used to manage JavaScript modules.
First of all, we need to add a button to our view and reference a file that will contain a JavaScript handler:
Open the app
/views file./welcome /index.html.erb Add the following code:
<h1>Hello, Rails!</h1> <button id="greet-user-button">Hello!</button> <%= javascript_pack_tag 'hello'%>
Apart from the existing static text within the
h1
tag, the view file contains:A button
tag
that adds a button with a specific identifier.The
javascript_pack_tag
helper method is used to create a script tag referencing the pack file. In our code, this should be the hello.js file that will be created in the next chapter.
To create a JavaScript file containing a code for handling a button click, follow the steps below:
In the Project view Alt01, select the app
/javascript directory./packs Press AltInsert and select JavaScript File in the invoked popup.
Specify the file name (hello in our case) and press Enter.
In the created hello.js file, add the following code:
function hello(name) { let greeting = "Hello, " + name + "!"; console.log(greeting); alert(greeting); } document.addEventListener('turbolinks:load', () => { const clickButton = document.getElementById("greet-user-button"); clickButton.addEventListener('click', (event) => { hello('JavaScript') }); });
In this script we've:
Created the
hello
function that writes a message to the web console and displays an alert dialog with this message.Appended an event listener to our web page to invoke the
hello
function when a user clicks a button.
To see our application in action, you need to start a web server.
Press Ctrl twice and start typing development.
Select the Development run configuration from the list and press Enter.
RubyMine will show the process of preparing the application to run.
Copy the http://0.0.0.0:3000
/welcome address used by a web server, insert it to the browser's address bar, and press Enter to see the welcome/index page. Then, click the Hello! button to see the alert./index
Thanks for your feedback!