Functions defined in application.js not working

Viewed 368

I'm working on a Rails 6 app and I'm trying to put some Javascript functionality into my app. The code I'm using is working on non Rails template but when I put the same code into Rails 6 app application.js folder the Javascript function is not working.

application.js

function hideButtin(){
  var element = document.getElementById("hide");
  element.style.display = 'none';
}

header.html.erb

<%= link_to "OWNER SIGN UP", signup_path, class: "button", onclick: "hideButtin()" %>

_form.html.erb

 <div id="hide">
   <%= f.check_box :owner %>
   <%= f.label :owner %>
 </div>
2 Answers

Yes, functions doesn't work like that in Rails 6, you need add it in window scope

function hideButtin(){
  var element = document.getElementById("hide");
  element.style.display = 'none';
}

window.hideButtin = hideButtin;

Give it a try.

Why not just write a real event listener instead of using onclick?

document.addEventHandler('addEventListener', 'click', function(e){
  var other_element = document.getElementById("hide");
  if (e.target.matches('.hide_on_click') && other_element) {
     other_element.style.display = 'none';
  }
});

<%= link_to "OWNER SIGN UP", signup_path, class: "button hide_on_click" %>

It does not mix content and behavior and you don't need to create a global. If you don't want to hardcode the id of the element you are hiding just add a data attribute with the target.

Related