Dylan L.
Dylan L.

Reputation: 1317

run scripts if on certain page - rails

Would it be a bad idea to run an if statement on each page load to check whether or not I should run a script. For example I have a really long javascript file that only needs to be run when using forms. But currently in each of my files I have included the document.addEventListener("turbolinks:load", function() which means it runs on every page load.

In my script I am tempted to write an if statement at the beginning of the file like so:

document.addEventListener("turbolinks:load", function() {
  controller = $('body').data('controller')
  action = $('body').data('action')
  if controller == foo && action == bar 
    runScripts();
  else
    return;
  function runscripts() {
    ...

I'm still somewhat new to using javascript with rails so I don't know of another way. Any suggestions?

Upvotes: 3

Views: 1506

Answers (1)

Rajkaran Mishra
Rajkaran Mishra

Reputation: 4942

You can scope the body element of the layout with the controller and action name.

<body class="<%= controller_name %> <%= action_name %>">
  <%= yield %>
</body>

Now by using the classes we added to the body of the layout, we can limit the pages certain functionality.

$(document).on("turbolinks:load", function() {
  if (!($(".foo.bar").length > 0)) {
    return;
  }
  //--- page specific js code after above condition ---
});

In this case, a small condition can prevent the page specific behaviour being triggered on pages it shouldn’t be.

For more clarity read this

Upvotes: 9

Related Questions