I want to use Javascript to manipulate image files in Rails.

Asked 1 years ago, Updated 1 years ago, 69 views

Assume you use the asset pipeline,

app/assets/images/1.jpg

If you placed an image file on the , you do not know how to specify the path when using Javascript.

For example, in a simple jQuery, in a js file (or script tag in an erb file),

$("button").click(function(){
  $("div").css("background-image", "url(1.png)");
});

But it doesn't work.

Could someone tell me?

The actual code is different, so I would appreciate it if you could tell me how to pass within js, not just in the css file.

javascript ruby-on-rails

2022-09-30 21:27

1 Answers

If it is erb, you should be able to refer to it using the following methods:

$("button").click(function(){
  $("div").css("background-image", "url(<%=asset_path'image.png'%>);
});


2022-09-30 21:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.