Slevin
Slevin

Reputation: 4222

Rails: How to access images in Javascript?

i'm pretty new to Rails and have a little question:

How can i access images in Javascript? SCSS, ERB, ... have methods like "image_path", but i didn't find something similar for Javascript.

I need it to specify the image URLs for the firefly plugin:

$.firefly({images : ['???/1.jpg', '???/2.jpg'],total : 40});    

Upvotes: 1

Views: 2217

Answers (2)

HungryCoder
HungryCoder

Reputation: 7616

if your image in /app/assets/images/ you can simply use

/assets/1.jpg

Similarly in css, you can use

url(/assets/1.jpg)

You can follow same thing when using in javascript.

$.firefly({images : ['/assets/1.jpg', '/assets/2.jpg'],total : 40}); 

Note: The above methods will cause problem when your rails app is in sub-directory. In that case use relative path. Asset pre-compilation will compile all assets in public/assets directory. so your structure may be like:

public -assets --images ---1.png --javascripts --stylesheets ---style.css

so from style.css, you can use relative path like ../images/1.png

Upvotes: 4

kiddorails
kiddorails

Reputation: 13014

When I needed to do this, I inserted the whatever image was required on the page under a div#class and set that class as hidden in my css. Then, in javascript, I could access the image from that div.

May not be ideal solution, but couldn't think of anything else because of asset pipeline.

Also, try accessing image from ./assets/image_name.jpg

Upvotes: 2

Related Questions