This recipe discusses loading Galleria and changing images from different webpage events.
Sometimes it's required to delay loading Galleria until sometime after a page is rendered. Additionally, you may want to trigger displaying a specific image in the gallery with an event outside the gallery. With this recipe, we'll configure Galleria to be loaded only when a user decides to view the gallery and images to be shown when a user performs a specific action outside of the gallery.
To get us started, create a file named trigger-exampe.html
in the development directory we've been working in with the following structure:
<!DOCTYPE html> <html lang="en"> <head> <script src="http://code.jquery.com/jquery.min.js"> </script> <script src="../galleria-1.2.8.min.js"></script> <script> /* Galleria initialization */ </script> </head> <body> <div id="galleria" style="height: 500px; display: none"> <!-- supply images here --> </div> <a id="show-gallery">Show Gallery</a> | <a id="show-image">Show Image 2</a> </body> </html>
Make sure to fill in the image HTML structure to test with. We'll fill in the Galleria JavaScript initialization code in the following example.
To accomplish this, we'll add event handlers for click events on the anchor tags to "Show Gallery" and "Show Image 2".
<script> $(document).ready(function(){ /* when the element with the id "show-gallery" is clicked, create the gallery. */ $('#show-gallery').click(function(e){ $(this).remove(); $('#galleria').show(); Galleria.loadTheme( '../themes/classic/galleria.classic.min.js'); Galleria.run('#galleria'); /* prevent the default link behaviour */ e.preventDefault(); }); $('#show-image').click(function(e){ var galleria = Galleria.get(0); if(galleria === undefined){ alert('Galleria not initialized yet.'); }else{ galleria.show(1); } e.preventDefault(); }); }); </script>
Here, we register click
event handlers for each of the anchor tags we added to the document. Rendering the gallery inside a click event is identical to registering as we have been doing throughout the book. Here, we're just doing the same inside the click event.
To show an image on a click
event outside the gallery, we use Galleria.get
to retrieve the current active Galleria instance active on the page. Then we use the galleria.show
method to show the second image of the gallery.