15

I'm trying to get the background image to change every 6 seconds and it's always a 404 error:

For example, the below appears in the JS console

http://localhost:3000/app/assets/images/ggb_mist.png 404 (Not Found) 

To simplify this I just tried a background-color to make sure it was working. See below:

$(document).ready(function() {
  function testing() {
    $('.holder').css('background-color', 'red');
  };
});

The above works. Now when I try to do the same with an image (which is located in app/assets/images/imagefilenamehere.png I always get a 404 error. I've tried:

filenamehere.png
../assets/images/filenamehere.png
../app/assets/images/filenamehere.png
../images/filenamehere.png

Why won't the below work?

$('.holder').css({'backgroundImage':'../assets/images/filenamehere.png'});

Any input on the matter is appreciated.

hexacyanide
  • 88,222
  • 31
  • 159
  • 162
Nubtacular
  • 1,367
  • 2
  • 18
  • 38

2 Answers2

21

You can use the .erb (embedded ruby) extension to allow rails path helpers in your .js files:

1) You save your original file (my_script.js) as my_script.js.erb with the image path helper:

$('.holder').css({"background-image":"<%= asset_path('filenamehere.png') %>"});

Also, make sure you have your asset pipeline set up correctly:

From the Rails Asset Pipeline guide (http://guides.rubyonrails.org/asset_pipeline.html)

2) Your javascript file (my_script.js.erb) is inside:

app/assets/javascripts/
lib/assets/javascripts/
vendor/assets/javascripts/
vendor/assets/somepackage/

3) Your file is referenced in the manifest (maybe app/assets/javascripts/application.js):

//= require my_script
Jaron Gao
  • 466
  • 3
  • 9
  • Thank you for the answer. the file was initially `welcome.js.coffee` so i commented out the coffee gem and made the file `welcome.js`. Now I've changed it to `welcome.js.erb` and applied the jQuery above. My `application.js` is indeed in `app/assets/javascripts/` and `//=require welcome` in `application.js` doesn't change anything. No errors in js console (I can get an alert to work). – Nubtacular Feb 26 '14 at 00:40
  • Sweet got it: See here section 2.3.1 http://guides.rubyonrails.org/asset_pipeline.html . Upvote for you though as you were basically right. – Nubtacular Feb 26 '14 at 00:50
9

This solved my problem: Section 2.3.1 of guides.rubyonrails.org/asset_pipeline.html

$('.holder').css("background-image","url(<%= asset_path('tree-rays.jpg') %>)");

Note that tree-rays.jpg is in app/assets/images (Rails 4 Application).

Nubtacular
  • 1,367
  • 2
  • 18
  • 38
  • That worked for me, instead of tranquilize's answer. The key was having the url(...) around the ruby expression, and using a comma instead of a colon. – Teemu Leisti Oct 08 '14 at 21:34
  • 1
    this is the best solution ever, but I think you can't use asset_path in .js file.. so what about that? – user1735921 Jan 12 '17 at 10:26