yellowreign
yellowreign

Reputation: 3638

Ruby on Rails - Referencing Image in Javascript

I'm using jquery.infinitescroll.js in my Rails 5.0 app. I have the script in my Vendor directory, and I'm trying to customize the JS to use a different image.

I can do it, if I set this property:

img: "/img/loading.gif", 

I tried adding the image in a directory called img in the Vendor directory, but that didn't work.

I also tried setting the property to "/image/loading.gif" and the image still couldn't be found. What's the best way to handle this?

Upvotes: 0

Views: 36

Answers (1)

luiscrjr
luiscrjr

Reputation: 7258

One approach is to append .erb extension to your jquery.infinitescroll.js.

And, in jquery.infinitescroll.js.erb, you can use the asset_path method:

{
   /* ... */
   img: '<%= asset_path('loading.gif') %>'
   /* ... */
}

You must move your image to the app/assets/images folder.

Or, if you want to use it in a custom folder, add this path to the assets search path with config.assets.paths << Rails.root.join("vendor", "images") in config/application.rb.

By the way, that's the way recommended by the docs:

2.3.3 JavaScript/CoffeeScript and ERB

If you add an erb extension to a JavaScript asset, making it something such as application.js.erb, you can then use the asset_path helper in your JavaScript code:

$('#logo').attr({ src: "<%= asset_path('logo.png') %>" });

This writes the path to the particular asset being referenced.

Upvotes: 1

Related Questions