Kyle Brown
Kyle Brown

Reputation: 303

How to move script in a view to a separate js file in Ruby On Rails?

I am using: Ruby version: 2.2 Rails version: 4.2

I am attempting to make use of the asset pipeline in terms of JavaScript, I understand and have working stylesheets, but I cannot separate my js from my view.

Example:

// view.html.erb 
<body> 
  <div id="slider"></div> 
</body> 


// assets/javascript/slider.js
$( "#slider" ).slider({
  min: 0,
  max: 10000,
  value: 0,
  slide: function( event, ui ) {
    $( "#SolarAmount" ).val(ui.value + " sq. ft.");
  }
});

But the slider is nowhere to be found. However, If I include the function inside the view.html.erb it works as expected. If anyone can offer some advice about how the pipeline works with javascript I would appreciate the help!

Upvotes: 2

Views: 1666

Answers (3)

staxim
staxim

Reputation: 1467

If you're fighting with turbolinks, you may need to put your js code inside a turbolinks ready function.

Something like this:

$(document).on("turbolinks:load", function(){
  $( "#slider" ).slider({
    min: 0,
    max: 10000,
    value: 0,
    slide: function( event, ui ) {
      $( "#SolarAmount" ).val(ui.value + " sq. ft.");
    }
  });
});

You'll know if you're fighting with turbolinks when you see your js working when you refresh the page but not when you navigate from another page in your app.

Upvotes: 0

Mario
Mario

Reputation: 1359

Make sure you're importing your application.js file in your app/views/layout/application.html.erb file.

It should have this line: <%= javascript_include_tag "application", "data-turbolinks-track" => true %>

Also make sure your app/assets/javascripts/application.js file is properly set up (most likely is)

Upvotes: 0

Christian
Christian

Reputation: 19740

Generally speaking, you should nearly always enclose that type of code in the jQuery ready function. If the javascript is at the top of the document, it will execute before the div exists.

The jQuery ready function executes code when the DOM is fully loaded. 99% of the time, this is what you'll want.

For example, you need to do this:

$(function() {
  $( "#slider" ).slider({
    min: 0,
    max: 10000,
    value: 0,
    slide: function( event, ui ) {
      $( "#SolarAmount" ).val(ui.value + " sq. ft.");
    }
  });
});

Make sure you're including the application javascript file in your template, as Mario suggests. Assuming you're using the jquery-rails gem, your application.js should look something like this:

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

As in, you need to make sure you include jQuery before all the other js files in the directory (require_tree .).

Upvotes: 1

Related Questions