Amend Image SRC and Append to Div

I have a HREF that contains an image:

<a href="#" class="small-gallery">
    <img src="001.jpg">
</a>

On clicking this image, a popup modal (Bootstrap) appears, and fills
the modal body (ie. the content of the modal) with the same image as
appears inside the HREF. ie:

$('.thumbnail').click(function(e){
  e.preventDefault();
  $($(this).parents('.small-gallery').html()).appendTo('.modal-body');
  $('#myModal').modal({show:true});
});

This all works great, but what I actually want to do is change the
image SRC that appears in modal body, so that it takes the SRC from the
image (ie. 001.jpg) and adds a string of “-m” before the image
extension, so it changes the image SRC to “001-m.jpg”

So the sequence of events would be:

Click .small-gallery href Grab image SRC from .small-gallery imgOutput full image tag in .modal-body but ensure the image SRC has “-m” before the .jpg extension

I’m sure it’s simple, but I’m having a mind dump and can’t get it working.

Thanks for your help in advance, and Merry Christmas!

J

Rather than split the string could you just not supply the new source in a data attribute and grab that instead.

e.g.

<a href="#" class="small-gallery">
    <img data-img-modal="001-m.jpg" class="thumbnail" src="001.jpg">
</a>

JS

$('.thumbnail').click(function(e){
  e.preventDefault();
  var myClone = $(this).closest('.small-gallery').clone();
  var theImg =  myClone.find('img');
  var newSrc = $(this).data('img-modal'); 
  theImg.removeClass('thumbnail').attr("src", newSrc);
  myClone.appendTo('.modal-body');
 $('#myModal').modal({show:true});
});

You would need to remove the image from the modal when it closes or you will keep adding an image each time you click.It’s probably better to add a default image to the modal and then just change the source of the modal with information from the data attribute.

1 Like

Perfect, Paul! Thank you very much. That makes absolute sense. Sometimes it’s difficult to see the wood for the trees and think of a different way to achieve the same result.

Thanks!

J

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.