简体   繁体   中英

Using erb in a coffeescript file to change background

I'm trying to have it so that when a user selects "white" from a dropdown, the background image of a div changes to a white image, and when they select "red", it changes to a red image etc.

I'm having to use coffeescript as I'm using the best in place gem as well. I'm new to coffeescript, so it could be a syntactical error, but any help would be much appreciated!!

user.js.coffee.erb:

jQuery ->
  $('.best_in_place').best_in_place()
  $('#background').css("background-image", "url("/assets/images/<% @user.background %>.jpg")")

The image is stored in the images folder in assets. The js.coffee.erb file is stored in the javascripts folder in assets. I'm getting the following error:

undefined method `background' for nil:NilClass

TIA!

I don't think it is possible that you can do it that way. In production environment, those javascripts should be precompiled and then served as static files. They will not change on each request to show different background to different users.

A possible solution is to set @user.background as a class of the background tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM