3

I have a line of javascript within my view in my rails app:

<script>

$(this).find("img").attr("src", "/assets/img5.png"); 

</script>

I have the image path hard coded as you can see. This is working fine locally, but is not working well on production because i'm serving the assets through a cdn.

How do I include an image tag without messing up the javascript?

4
  • Whats the path of the asset on the CDN? Commented Apr 8, 2014 at 0:20
  • I'd like to completely avoid hard coding it. Commented Apr 8, 2014 at 0:24
  • Well yeah, but the answer depends on how the CDN path is structured. Commented Apr 8, 2014 at 0:25
  • Oh sorry! cdn.example.com/assets Commented Apr 8, 2014 at 0:27

2 Answers 2

4

After playing around a bit, I found something that works:

<script>

$(this).find("img").attr("src", '<%= asset_path 'img5.png' %>'); 

</script>

Looks like asset_path gets the job done.

Sign up to request clarification or add additional context in comments.

2 Comments

yea, looks like it works. asset_path has the host coming from config file which automatically appends the cdn path.
Yup! Works like a charm! :)
1

I would be using soemthing like

jQuery('img[src*="signup_arrow.png"]')

without changing much of the current code. Here src* indicates that "signup_arrow.png" can be a substring of the image src.

Typically CDN urls would be http://cdn.example.com/signup_arrow.png?13304 to using the selector to find the given image name as substring helps.

1 Comment

can you paste the error response and code you tried, it helps debug

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.