Home > Software engineering >  How can I create and trigger a simple onclick JS function in Rails 7
How can I create and trigger a simple onclick JS function in Rails 7

Time:11-29

How can I get an onclick function to trigger in a Rails 7 view?

I added a simple function:

// app/javascript/application.js
function myTest(myVar){
    alert(myVar);
};

myTest("test1");

The alert for "test1" does trigger on page load. However, I want to trigger this in an HTML onclick attribute within my view:

// my view
<a href="#" onclick="myTest('test2');">test</a>

However, the browser console says that the myTest function is not defined. I do see that the function ends up in my application.js file that the browser is loading.

// compiled application.js from asset pipeline
(() => {
  // ... all of the other rails JS here

  function myTest(myVar) {
    alert(myVar);
  }
  myTest("test1");
})();

Shouldn't I be able to trigger this directly from the console also? This also gives me the error that the function does not exist.

myTest("test3");

edit: I think all of the code in Rails is being put into an IIFE which is purposely not loaded in the global scope.

CodePudding user response:

You could assign a function to the window object using something like

window.myTest = function myTest(myVar) {
  alert(myVar);
};

This should make it available in the global scope.

  • Related