Anna_Natorilla
Anna_Natorilla

Reputation: 157

Where to place the javascript file to relate it with a particular view folder in Rails?

In my app/views/phrases/_forms.html.erb, I have a button with an id which I want to show or hide a particular section with id preview-section.

<%= button_tag(type: 'button', class: "btn btn-default", id: 'preview-button') do %>
    Preview
<% end %>

<section id="preview-section"> Some Content </section>

I'm not sure where to place the jquery in the rails app.

$('#preview-button').click(function () {
    alert("Preview button was clicked");
});

Upvotes: 0

Views: 36

Answers (2)

user3506853
user3506853

Reputation: 814

1) You can add this code in custom js file also:-

# app/assets/javascripts/custom.js
$(document).on('click', '#preview-button', function(){
    alert("Preview button was clicked");
});

include custom.js in application.js file:-

//= require custom.js
or
//= require_tree .(It will includes all js files in javascripts folder)

2) You can make a folder with name phrases in javascripts folder and make js file inside /app/assets/javascripts/phrases, then require this folder in application like:-

//= require_tree ./phrases (requires all js files in phrases folder)

Upvotes: 1

richfisher
richfisher

Reputation: 951

app/assets/javascripts/phrases/, it should be Rails style.

All js under app/assets/javascripts will compress and minified to application.js in production.

$(function(){
  $('#preview-button').click(function () {
    alert("Preview button was clicked");
  });
})

Upvotes: 1

Related Questions