Ad

Ruby On Rails Call Javascript Function

- 1 answer

Here is my application.html.erb with the tag h1 and onclick execute JS function greatTutorial() .

## application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Dealabs</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <div class="container">
      <%= render "layouts/navbar" %>
      <h1 onclick="greatTutorial()">Hello World</h1>
        <% if notice %>
          <p class="notice alert alert-info"><%= notice %></p>
        <% end %>
        <% if alert %>
          <p class="alert alert-danger"><%= alert %></p>

        <% end %>
      <%= yield %>
    </div>
  </body>
</html>

And my javascript/pack/application.js

##javascript/pack/application.js

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

function greatTutorial() {
    alert('Rails Guides are the best');
}

I followed multiple ask on that, but nothing work. If I replace my function onclick by h1 onclick="alert('danger')" is working fine. But I don't understand why my function greatTutorial is undefined (never exist).

Thanks !

Ad

Answer

There is a workaround, though. In Rails 6 you can change the function signatures from:

function myFunction() { ... }

to:

window.myFunction = function() { ... }

So according to your code try this :-

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")


window.greatTutorial = function() {
    alert('Rails Guides are the best');
}
Ad
source: stackoverflow.com
Ad