Jquery – Automatically call Twitter bootstrap-modal.js for tag

bootstrap-modalimagejquerythumbnailstwitter-bootstrap

Fancybox has a feature where it adds the fancybox class for each image on a page using something like this jQuery(thumbnails).addClass("fancybox").attr("rel","fancybox").getTitle();.

I would like to do something similar with the Twitter Bootstrap Modal for the <img> tags so that I don't have to make a call for each and every image. Essentially, I want to use the bootstrap-modal.js as an inline image viewer, like a Lightbox/Fancybox.

I found this: http://blueimp.github.com/Bootstrap-Image-Gallery/ but the demo shows you have to make a call for each and every image.

How would I go about doing this?

Best Solution

Using Bootstrap 3 this is how I managed to get it working without any additional plugin using just Bootstrap's built-in Modal component:

Add a modal in your HTML page with an <img> tag that has an empty src like this:

<!-- Photo Modal -->
<div class="modal fade" id="photo-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">

               <img src="" />

    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

Now let's say you have your thumbnail images inside links like this:

<a class="thumbnail" data-imgpath="pathToImage" data-toggle="modal" href="#">
    <img alt="PhotoName" src="pathToImage">
</a>

Use this jQuery code to show the thumbnail image in full size inside the modal:

$(function()
{     
    $('a.thumbnail').click(function(e)
    {
        e.preventDefault();

        var imgPath = $(this).data('imgpath');

        $('#photo-modal img').attr('src', imgPath);

        $("#photo-modal").modal('show');
    });

    $('img').on('click', function()
    {
        $("#photo-modal").modal('hide')
    });
});

Add this CSS to center the image inside <div class="modal-dialog">:

#photo-modal .modal-dialog
{
    text-align:center;
    display:table;
    padding: 0;
    margin-top: 30px;
}

Idea taken and adapted from palmerio - Modal images