fynn
fynn

Reputation: 143

Show original photo on click Rails

Hi I am looping through uploaded photos and showing thumbnails. I'm trying to display the original photo when someone clicks on the thumbnail. The problem is that it only works on the first thumbnail in the loop. Do I need to give each thumbnail a individual id or how can I get it to work on every thumbnail? Any tips? :)

My show:

    <% @project.assets.each do |asset| %>
      <% if asset.photo.file? %>
        <li class="thumbnail col-md-2">
           <a id="thumb" href="#">
             <%= image_tag asset.photo.url(:thumb)  %>
           </a>
        </li>
      <% end %>
        <div id="popup">
          <%= image_tag asset.photo.url(:original) %>
        </div>
    <% end %>

My javascript:

<script type="text/javascript">
$(document).ready(
    function() {
        $("#thumb").click(function() {
            $("#popup").toggle();
        });
    });
</script>

Thanks :)

Upvotes: 0

Views: 2491

Answers (2)

Adeptus
Adeptus

Reputation: 683

you have to use class "thumb" except id. because id is uniq so only first working.

the same with "popup" id because always will be show first image. so you can make like:

<% @project.assets.each do |asset| %>
  <% if asset.photo.file? %>
    <li class="thumbnail col-md-2">
       <a id="asset-#{asset.id}" class="thumb" href="#">
         <%= image_tag asset.photo.url(:thumb)  %>
       </a>
    </li>
  <% end %>
    <div id="popup-asset-#{asset.id}">
      <%= image_tag asset.photo.url(:original) %>
    </div>
<% end %>

<script type="text/javascript">
$(document).ready(
    function() {
        $(".thumb").click(function() {
            $("#popup-" + this.attr("id")).toggle();
        });
    });
</script>

Upvotes: 1

m_x
m_x

Reputation: 12564

Try this :

<% @project.assets.each do |asset| %>
  <% if asset.photo.file? %>
    <li class="thumbnail col-md-2">
       <%= link_to asset.photo.url(:original), class: :popup_link, target: :_blank do %>
         <%= image_tag asset.photo.url(:thumb)  %>
       <% end %>
    </li>
  <% end %>
<% end %>

<div id="popup"></div>

<script type="text/javascript">
  $(document).ready(function() {
     $(".popup_link").click(function(e) {
        e.preventDefault();
        $("#popup").html( $('<img>').attr('src', this.href) );
     });
  });
</script>

what we're doing here is that on click, we fill the popup div with an image tag whose src attribute is the clicked link's href attribute value.

The good thing about this approach is that it degrades gracefully when javascript is desactivated (clicking on the link will open the full image in a new tab). As you don't load all full images (just to hide them), your page load time will likely decrease, too.

Upvotes: 3

Related Questions