Twitter bootstrap-modal for images

trante picture trante · Apr 28, 2012 · Viewed 16.3k times · Source

I have a page which includes details of the registered users. Every html table includes 80-90 users. For every user there is a $username variable. I normally show their pictures in a table like the code below.

print "<a href=\"small-avatar-$username.jpg\" target=\"_blank\">
<img src=\"big-avatar-$username.jpg\">
</a>";

But the user can open images in a new tab. I want to show big avatars easily. My first choice was lightbox-jquery. But because i use twitter-bootstrap in my site, i decided to use default bootstrap and jquery features.

I saw that there is "bootstrap-modals". When user clicks link, i don't plan to show anything more than i big picture.

I tried this:

print "<a href=\"#$username" data-toggle=\"modal\" class=\"img-modal\" >
        <img src=\"small-avatar-$username.jpg\" ></a>";
print '</td>';

.

print "<div id=\"$username\" class=\"modal\">";
       <img src=\"big-avatar-$username.jpg\">
print "</div>";

.

<script type="text/javascript" id="js">
        $('#username').modal();
</script>

I suppose putting $('#username').modal();
for every user to my page will make HTML file huge.

But then I tried class name of anchor like this: $('.img-modal').modal();
But this didn't work.

What would you recommend in this situation?

Answer

baptme picture baptme · Jul 9, 2012

I would recommend you to use a HTML5 Custom Data Attributes in your <a> tag to identify the username and keep your img-modal class.

"<a href="#myModal" data-username='".$username."' class="img-modal">...

Trigger the call to modal on click on .img-modal (you don't need the data-toggle="modal")

$('.img-modal').click(function(event) {

You can get the value of the username by using

var username = $(this).attr('data-username')

Since you have the username you can replace the src property of your <img> tag in your unique modal with something like.

$("#img-in-modal").attr("src","big-avatar-" + username + ".jpg")

And open your modal

$('#myModal').modal('show')

And finally, make sure bootstrap-modal.js or boostrap.js is included.