Petros Kyriakou
Petros Kyriakou

Reputation: 5343

How to change image_tag source using javascript

I am trying to create a toggle which is basically two images. A plus icon and a minus icon.

Unfortunately if i use "assets/" it works on development but not on production - it wont find the image. I understand its probably because of asset digesting.

$(".directions-and-alternative-options-toggle").on("click", function(){
    if($(this).hasClass("collapsed")){
      $(this).find("img").attr("src", "/assets/minimize-icon.png");
    } else {
      $(this).find("img").attr("src", "/assets/expand-icon.png");
    }
  });

  <a class="directions-and-alternative-options-toggle collapsed" type="button" data-toggle="collapse" data-target="#reveal-key-directions-in-<%= event.event_id %>" aria-expanded="false" aria-controls="collapse1">
      <%= image_tag "expand-icon.png", class: "expand-icon pull-right" %>
  </a>

is there any way to get the digested asset path?

Upvotes: 2

Views: 1193

Answers (2)

Ahmed Samir Shahin
Ahmed Samir Shahin

Reputation: 558

How about making use of jQuery data attributes like this:

In the view:

<%= image_tag 'expand-icon.png', class: 'expand-icon pull-right', data: { collapse_icon: asset_path('collapse-icon.png'), expand_icon: asset_path('expand-icon.png')} %>

In the JS:

$('.directions-and-alternative-options-toggle').on('click', function(){
  var $img = $(this).find('img');
  if($(this).hasClass('collapsed')){
    $img.attr('src', $img.data('collapse_icon'));
  } else {
    $img.attr('src', $img.data('expand_icon'));
  }
})

Upvotes: 1

Antonio Ganci
Antonio Ganci

Reputation: 515

I think you have two options:

1 - Move the images (minimize-icon.png and expand-icon.png) to the public folder of your project so they are not precompiled.

2 - Use asset_path:

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

Upvotes: 3

Related Questions