2

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 !

1
  • Are you using Rails 6 ?? Commented Feb 10, 2020 at 9:27

2 Answers 2

2

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');
}
Sign up to request clarification or add additional context in comments.

2 Comments

Oh ! i search so long time thanks you is work fine !! Why the function declare like that (function myfunction() {}) not work now ?? Thanks !
I am not confirmed may be its rails 6 syntax. Last month I was also stuck in same condition so I solved like above after long hit and try method. :)
0

Rename your application.js to javascript.js or main.js

This is required if you have application.css and application.js inside packs directory. As webpack deals with css files in special way and create .js extensions.

Check out similar issue reported here for more details.

Comments

Your Answer

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