Nick Gilbert Nick Gilbert - 11 months ago 55
Javascript Question

Ruby on Rails, change source of image with JavaScript

I have a JavaScript function which changes one of the images on my web page when the user scrolls down

$(window).scroll(function() {
if ($(document).scrollTop() > 0) {
else {

function switchToAnimated() {
if ($(window).width() > 768) {
$('body').css('padding-top', '0');
$('#logo').attr('src', '../assets/blue_logo.png')
$('#logo').css('width', '15vw');
$('.navbar').css("background-color", 'transparent');

function switchToStatic() {
$('body').css('padding-top', '50px');
$('#logo').attr('src', '../assets/white_logo.png')
$('#logo').css('width', '7.5vw');
$('.navbar').css("background-color", '#3B98F2');

My application is built on Ruby on Rails. The slim markup looks like this

a href=""
= image_tag("white_logo.png", alt: "logo", id: "logo")

On my localhost the functions work properly but when we launch the site to production the files are missing. I know rails sucks everything into a common directory but I don't know how to fix this to get the image to behave the way I want it to on both localhost and production. I tried taking away the '../assets/' reference and just pointing to the file but that did not work on either localhost or production.

Answer Source

Rails is using asset pipeline which adds fingerprints to each js, css and other assets file. So you cannot just fetch file by its name, you need to use the name with fingerprint. image_tag helper will generate correct paths on production, so what you need to do is to somehow inject those paths into javascript.

For example you can do something like this:

  var blueLogoPath = "#{asset_path('blue_logo.png')}";
  var whiteLogoPath = "#{asset_path('white_logo.png')}";

And then

$('#logo').attr('src', whiteLogoPath);