Dario
Dario

Reputation: 757

Jquery take src path of img tag inside div-->a-->img

I'm make a gallery that contain some different image and with onClick they open modal and show a zoom of the image.

I use same method with Portfolio but here i have only 4 item so i create 4 different modals that show description etc etc...

Now with image i want a single modal that change image to show with users onClick.

The divs that contai images are structured like that:

   <div class="col-sm-3 galleria-item">
        <a class="galleria-link" href="#galleriaModal" data-toggle="modal">
          <div class="caption">
            <div class="caption-content">
              <i class="fa fa-search-plus fa-3x"></i>
            </div>
          </div>
          <img class="img-fluid" id="1" data-toggle="modal" data-target="#galleriaModal" src="foto/portfolio/portfolio1.jpg" alt="">
        </a>
      </div>

And here the modal:

<div id="galleriaModal" class="modal fade" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body">
                    <img class="img-responsive" src="" />
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>
                </div>
            </div>
        </div>
    </div>

And here the jQuery:

// Modal for gallery images
  $(function () {
        $('#galleriaModal').on('show.bs.modal', function (e) {
            var image = $(e.relatedTarget).attr('src');
            $(".img-responsive").attr("src", image);
        });
  });

Following this link

The problem is that the site show modal when i click image but don't show image inside...and with inspect code i see src = unknown...

Where i'm wrong?

EDIT

i'm sure that the problem is that var image = $(e.relatedTarget).attr('src');don't take the path of image of the div that user click! How can i take the src of image inside div->a->img of user click?

Upvotes: 0

Views: 1174

Answers (1)

James
James

Reputation: 22227

e.relatedTarget is the <a> tag not the image, however it's easy to get the image once you have the anchor:

    $('#galleriaModal').on('show.bs.modal', function (e) {
        var image = $(e.relatedTarget).find('img').attr('src');
        $(".img-responsive").attr("src", image);
    });

Upvotes: 1

Related Questions