0

I have an image link that looks like this:

<a href="#user-image-modal" data-toggle="modal" data-id="<%= image.id %>"><img class="user-photo" src="<%= image.picture.medium.url %>" alt="" /></a>

and a modal that looks like this:

  <div id="user-image-modal" class="modal" tabindex="-1" role="dialog" aria-labelledby="user-image" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        </div>
        <div class="modal-body">
          <img src="" alt="">
        </div>
        <div class="modal-footer">
        </div>
      </div>
    </div>
  </div>

When the image link is clicked I want to open a larger version of the image. The url of the image is obtained from a carrierwave helper UserImage.find(id).picture.large.url.

My js.erb file:

  $('#user-image-modal').on('show.bs.modal', function (event) {
    var link = $(event.relatedTarget)
    var photo = link.data('id')
    var modal = $(this)

    // What comes next?
  })

I need to set the src attribute in the img tag of the modal with UserImage.find(photo).picture.large.url. The photo variable corresponds to the id of the UserImage record. How can I use the photo variable to get the correct url. I don't think I can use the photo variable inside erb tags.

1 Answer 1

1

Add the large picture url to the link as a data attribute, like it is done with the id attribute. Then (on click) get the url and do whatever you want.

<a href="#user-image-modal" data-toggle="modal" data-url="<%= image.picture.large.url %>">
  <img class="user-photo" src="<%= image.picture.medium.url %>" alt="" />
</a>

$('#user-image-modal').on('show.bs.modal', function (event) {
  var link = $(event.relatedTarget);
  var imgSrc = link.data('url');
  var modal = $(this);

  modal.find(".modal-body img").attr('src', imgSrc);
})

Another way is to send an AJAX query with the given id to get the picture.

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

Comments

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.