All threads / Page Specific Javascript

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Page Specific Javascript

Michael Victor asked in Javascript

I just came across this article that talks about a gem that allows you to implement cleanly space specific javascript.

http://brandonhilkert.com/blog/page-specific-javascript-in-rails/

However, it was written in Feb 2014, does anyone know if there is now a better way to do this?

This is a really great question Michael. Do you have examples of what kind of Javascript you intend to run on specific pages? I can give you some generic advice, but it's always easier to understand with some examples.

We'll im looking at loading some elements via AJAX on page load on certain pages. I could check for the existence of certain elements and start making the AJAX calls but I'm guess there are simpler ways.

And I'm thinking that keeping the JS and the Rails code as separate as possible is generally a good idea.

That's actually what I would recommend doing. If you set up your JS to look for data-behavior tags like I covered in this episode you can load things into those tags.

The best way is not to really have page specific javascript, but instead to have these little widgets that can be reused anywhere by detecting things on the page. It'll keep the JS and Rails code very separate and the flexibility of making it not tied to specific pages helps a lot in the future.

I had to do something like this in a specific circumstance. The solution I used was to create a unique body class for each page with interpolation.
In HAML:
%body{:class => "#{controller_name}-#{action_name}"}

In ERB:
<body class="<%= controller_name %>-<%= action_name %>">

Then I can just use the unique controller/action_name class to as a JS hook.

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 37,629+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.