Reputation: 7103
I have a jquery function that's supposed to change the background of the page. I want the background to be an image in the app/assets/images directory. However, I'm confused as to the proper way to reference the image with the asset pipeline.
Here's the line I have now:
$('body').css("background-image", "url('welcome.png')");
What's the best way to access the image in the url parameter?
Upvotes: 1
Views: 4060
Reputation:
In my opinion, You need to use the .erb (embedded ruby) extension to allow rails path helpers in your .js files. If your js file (balabala.js for example) is in asset/javscripts/, change its name to balabala.js.erb, and then use:
$('body').css({"background-image":"<%= asset_path({'filenamehere.png') %>"});
Require this file in your asset/javscripts/application.js
//= require balabala
Then it should work
Upvotes: 0
Reputation: 4703
This is covered in the documentation:
http://guides.rubyonrails.org/asset_pipeline.html#coding-links-to-assets
You should use the methods described in "2.3.3 JavaScript/CoffeeScript and ERB", which would mean adding the .erb extension to your JS file, and using asset_path.
Another approach that's more elegant would be to move your image to a class definition in a css.scss file and then adding that class in your jQuery:
.welcome {
background-image: url(image-path('welcome.png'));
}
and in your jQuery:
$('body').addClass("welcome");
Upvotes: 6
Reputation: 1662
Try this:
$('body').css("background-image", "url('/assets/welcome.png')");
In order to access assets in the pipeline, you have to specify the assets
folder.
I've been trying to find where I read this, but Rails basically converts all asset helper urls to something like /assets/asset.png
or like /assets/stylesheet.css
so you should be able to do the same by just specifying the assets
folder in your source url.
Upvotes: 5
Reputation: 18855
$('body').css("background-image", "url('/app/assets/images/welcome.png')");
?
Assuming app is at the document root.
Upvotes: 0