Bitwise
Bitwise

Reputation: 8461

Replacing images with jquery - js.erb - Rails

I have a ajax call right now that changes the state of an object. When the click action happens I also want it to change the background image of that particular object in the UI. I'm trying to find the best way of doing this. I've tried the replaceWith method but it was printing text and not image. If anyone know of an easy way to do this that would be great, Thanks.

View

<tbody>
  <tr class="<%= snitch.classes %>">
    <td>
        <%= link_to "<span id='snitch_#{snitch.token}_icon' class='icon led'></span><span>#{snitch.name}</span>".html_safe, snitch_path(snitch), class: "name"%>
    </td>
    <td class="interval"><span class="vspace"><%= snitch.interval %></span></td>
    <td class="last-checked">
      <span class="vspace">
        <% if snitch.source.checked_in_healthy_at %>
          <span data-tooltip="Checked in healthy at UTC(<%= snitch.source.checked_in_healthy_at.to_i %>) || LOCAL(<%= snitch.source.checked_in_healthy_at.to_i %>)">
            Last seen <strong><%= snitch.checked_in_healthy_at(title: nil) %></strong>
          </span>
        <% else %>
          <strong><%= snitch.checked_in_healthy_at %></strong>
        <% end %>
      </span>
    </td>
    <td class="snitch-controls" data-icons="<%= snitch.pauseable? ? "5" : "4" %>">
      <%= render 'menu', snitch: snitch %>
      <nav class="snitch-states" >
        <% if snitch.pauseable? %>
          <%= link_to 'Pause', pause_snitch_path(snitch, remote: true), class: 'icon icon-pause pause',
            data: { tooltip: "Pause" },
            rel: "modal:open" %>
        <% end %>

        <%= link_to 'Delete', delete_snitch_path(snitch), rel: 'modal:open',
          data: { tooltip: "Delete" },
          class: 'icon icon-delete delete', title: "Delete #{snitch.name}" %>
        </nav>
    </td>
  </tr>
</tbody>

JS

 $('#snitch_<%= @snitch.token %>_icon').append("")

This is obvi incomplete attempt at what I'm trying to do but something like this? maybe?

Upvotes: 0

Views: 112

Answers (1)

Uzbekjon
Uzbekjon

Reputation: 11813

It looks like all links share a common class name. So, it is better to select your links by that CSS class, rather than each by its ID. Also, an easy way of doing it would be to simply add additional class on click and change the background image in your CSS file.

Something like this:

$('.name').on('click', function(e){
  $(this).addClass('clicked');
});
.name {
  background-image: url('first.png');
}

.name.clicked {
  background-image: url('changed-image.png');  
}

Upvotes: 1

Related Questions