0

I am attempting to load a javascript file onto my rails application, but only for a specific page in my application, not the homepage. How would I get my javascript file to load for a specific page is using rails.

The javascript I have now, located in programs.js in assets/javascript, looks like this:

document.addEventListener('DOMContentLoaded', (event) => {
 let program = document.getElementsByClassName('program-name')
 console.log(program)
 })

Again, the code itself works fine. The problem is that it executes for the homepage, and not for any particular page that I want it to. How would I go about getting the code to execute for a specific page within my rails application?

2 Answers 2

3

Why wouldn't you add the javascript tag to the View you want it to run on?

If you wanted a bit better rendering speed, you could add a end-of-page yield to your layout and then specify your javascript in the View like this:

layout/application.html.erb

<!DOCTYPE html>
...
  <%= yield(:scripts) %>
</body>
</html>

view/.../index.html.erb

<!-- regular view code here -->
...

<% content_for :scripts %>
  <%= javascript_tag do %>
    document.addEventListener('DOMContentLoaded', (event) => {
      let program = document.getElementsByClassName('program-name')
      console.log(program)
    });
  <% end %>
<% end %>
Sign up to request clarification or add additional context in comments.

2 Comments

Hadn't thought of that! let me try
@JonathanReiser My pleasure! Please accept the answer to close the question.
1

An other way is to do the following:

app/views/layouts/application.html.erb

<body class="<%= controller_name %> <%= action_name %>">
<!-- This will add your page's controller and action as classes, for example, "blog show" -->

Then, in your script file, you can do the following:

if($('body').is('.yourcontroller.youraction'){
  // Do something
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.