RubyMine 2022.2 Help

Add a JavaScript asset to a Rails application

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.

Update a view

First of all, we need to add a button to our view and reference a file that will contain a JavaScript handler:

  1. Open the app/views/welcome/index.html.erb file.

  2. 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.

Add a JavaScript handler

To create a JavaScript file containing a code for handling a button click, follow the steps below:

  1. In the Project view Alt+1, select the app/javascript/packs directory.

  2. Press Alt+Insert and select JavaScript File in the invoked popup.

    New File
  3. Specify the file name (hello in our case) and press Enter.

    New JavaScript File
  4. 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.

Start a web server

To see our application in action, you need to start a web server.

  1. Press Ctrl twice and start typing development.

  2. Select the Development run configuration from the list and press Enter.

    Run Development configuration
  3. RubyMine will show the process of preparing the application to run.

    Rails server output
  4. Copy the http://0.0.0.0:3000/welcome/index 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.

    Rm new js browser click
Last modified: 09 August 2022