I'm having trouble attempting to dynamically add images, since lightbox2 (by lokesh dakar) is initialized after document load by existent html coded images and it doesn't parse the document anymore after the first time.
If i try to add new images with javascript (appending them in the body for example) they are not added to the lighbox groups.
Documentation in official website doesn't seems to describe any scripted method
Anyone with experience can help me? solution with jquery are really welcome, but i can handle well vanilla js too.
Code sample:
HTML
<body>
<div id="container">
<a href="images/image-2.jpg" data-lightbox="roadtrip">Image #2</a>
<a href="images/image-3.jpg" data-lightbox="roadtrip">Image #3</a>
<a href="images/image-4.jpg" data-lightbox="roadtrip">Image #4</a>
</div>
<!-- where 'Image #X' = <img src="images/thumb/image-X.jpg>" -->
<div id="loadmore">load more images</div>
<script src="path/to/lightbox.js"></script>
<script>
/* see below for the script */
</script>
</body>
javascript
$(function(){
$('#loadmore').click(function(){
//ajax request for more images.
//load them with all the needed properties...
//then put them into the container:
var IMG = $('<a href="images/image-10.jpg" data-lightbox="roadtrip">'+
'<img src="images/small/image-10.jpg">'+
'</a>');
//magic here... add IMG to roadtrip lightbox group!!!
//probably something like lightbox.groups['roadtrip'].add(IMG)
//but i'm only speculating
$('#container').append(IMG)
});
})
After a couple of hours spent on testing and reading the code, I came up with this magic code:
//set album values
IMG = $('<a href="...">')
.attr('data-lightbox','roadtrip')
.append('<img src="...">')
//lightbox open:
IMG.click(function(){
lightbox.start($(this));
return false;
})
some helpful tips:
don't set data with
$(...).data('lightbox','group')
, since lightbox uses the selector$('a[data-lightbox]')
each time a link is clicked. Instead, you should use$(...).attr('lightbox','group')
.lightbox.album
is a temporary variable which you don't need to deal with.
To add existing img tags to be lightboxified on their own (without gallery functionality) one could use something like:
$('img')
.wrap(function(index) {
return '<a href="'+$(this).attr('src')+'" data-lightbox="image-'+index+'"></a>';
});
Just add it BEFORE inserting the lightbox.js
来源:https://stackoverflow.com/questions/34454681/lightbox-2-how-to-add-dynamically-images-via-javascript