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 !
-
Are you using Rails 6 ??code_aks– code_aks2020年02月10日 09:27:16 +00:00Commented Feb 10, 2020 at 9:27
2 Answers 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');
}
2 Comments
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.