1

I am trying to add custom JS to my Rails 7 project. I followed the instructions on this StackOverflow answer.

But I'm still not able to use custom JS in my view.

Here is my main.js:

function sayHi() {
    console.log("hi");
}

window.sayHi = sayHi;

Here is my view (index.html.erb):

<div>
  <button type="button" onclick="sayHi()">Click Me!</button>
</div>

When I click the button, in the console it just says:

Uncaught ReferenceError: sayHi is not defined

I'm really not sure how to access the custom JS from my view.

Here is a link to my project I uploaded to DropBox.

Slaknation
  • 2,124
  • 3
  • 23
  • 42
  • 2
    Better solution - just stop writing JS like its 2005 and [attach an event handler](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener). You'll thank me later. – max Dec 11 '22 at 08:39

2 Answers2

1

You need to expose the function to the global scope.

window.sayHi = sayHi;
javiyu
  • 1,336
  • 6
  • 9
1

So I am going to post this as a complete answer to anyone who wants to add javascript to their Rails 7 project:

  1. Create your custom JS file in app/javascript/custom/main.js (or whatever file name you like):

    function sayHi() {
        console.log("hi");
    }
    
    window.sayHi = sayHi;  // You must have this to expose your functions
    

    (or you can use an event hanlder instead)

  2. Go to config/importmap.rb and add the following:

    pin_all_from "app/javascript/custom", under: "custom"
    
  3. Go to app/javascript/application.js file and add the following:

    import "custom/main"
    
  4. Run In your terminal:

    rails assets:precompile
    
  5. Start your rails server. Voilà

Slaknation
  • 2,124
  • 3
  • 23
  • 42