简体   繁体   中英

Adding Captions to Bootstrap Responsive Modal Image Gallery

I have a responsive modal image gallery through bootstrap and I'm a beginner at coding. My images were successfully sliding forward and backwards until I tried adding captions.

I've added hover captions to every image using this in my javascript:

  $(".popup").wrap('<div class="alt-wrap"/>')

  $('.modal-body>caption').remove();

   $(".popup").each(function() {
   $(this).after('<p class="alt">' + $(this).attr('alt') + '</p>');

})

Now, whenever I click my modal image, the hover caption works fine but once I click next/prev, the old images still remain.

How do I remove the old images/captions when I click next/prev through my modals?

The rest of my js looks like this:

 var imagesList = $("div#imagesList");
    var imagesListLength = imagesList.children().length;

    var showImageGallery = function(imageNumber){

        $('.modal-body>img').remove();

        $('#imageModal').modal('show');


        var image = imagesList.children()[imageNumber];
        $(image).clone().appendTo('.modal-body');

        $("#currentImageNumber").text(imageNumber);

    }

    var nextImage = function(){

        $('.modal-body>img').remove();

        var nextNum = parseInt($("#currentImageNumber").text());
        if(nextNum == imagesListLength-1){ nextNum = -1;}
        $("#currentImageNumber").text(nextNum+1);

        var image = imagesList.children()[nextNum+1];
        $(image).clone().appendTo('.modal-body');

    }


    var previousImage = function(){

        $('.modal-body>img').remove();

        var previousNum = parseInt($("#currentImageNumber").text());
        if(previousNum == 0){ previousNum = imagesListLength;}
        $("#currentImageNumber").text(previousNum-1);

        var image = imagesList.children()[previousNum-1];
        $(image).clone().appendTo('.modal-body');


    }

$(window).keydown(function(event) {
  if (event.key === 'ArrowLeft') {
    previousImage();
  } 
  if (event.key === 'ArrowRight') {
    nextImage();
  }
  if (event.key === 'Escape') {
    $('#close-modal').trigger('click')
  }
})

I just had to add:

 $('.modal-body>.alt-wrap').remove();

under

var showImageGallery = function(imageNumber){

and

  $('.modal-body>.alt-wrap').remove();

to my .popup, nextImage, and previousImage functions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM