0

I have been Googling and beating my head up against a wall for 2 days and now I finally just need to ask you guys.

I want to simply create a Javascript file in Rails 6 and then call the function on a button in an erb file.

THAT'S IT.

Why is this not the simplest thing in the world?

After realizing that I was getting 2 different sets of instructions from the internet, one for rails 5 and previous and the other for rails 6, I tried looking for specifically Rails 6 answers. They were still much too complicated for such a simple problem and often were about bringing in external libraries. I don't want external libraries. I want my own javascript. And I want to call it in my erb files.

I appreciate anyone helping me out on this.

3
  • If you want a specific example. Literally a function called test() in a test.js file that alerts "hello world". From my javascript file to my erb file button. Commented Feb 9, 2020 at 13:39
  • Can you show us what have you done so far? Commented Feb 9, 2020 at 13:54
  • Assume that i've just created a rails new. I have my file structure, i have webpack and yarn. Maybe I've created a route, controller, model, and view. and I have an index page and I just want one button that when I click on it the alert from my javascript file test.js is working. Where am I putting the file test.js and how is my index file going to know about it? Commented Feb 9, 2020 at 15:33

1 Answer 1

1

Assuming you have application.js already in packs directory, create a new file custom.js in the same directory, since you want this to be accessible everywhere, you need to put it in window scope, add this in the file

window.testFun = function(){
  alert('Hello World!');
}

Then require the file in application.js

require("custom")

Now you can call this onclick in erb file in application.

<%= link_to 'Test', '#', onclick: "testFun()" %>

or

<%= link_to 'Test', "javascript:testFun()" %>

Give it a try.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. That's literally all I needed. You are the best!
@AndrewRichards Happy to help!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.