Bootstrap Gallery and Modal with Carousel

An Easy Bootstrap Gallery with a Pop-up Modal Carousel

December 28, 2016


The purpose of this post is to illustrate an easier way to create a Bootstrap gallery with a modal pop-up window that also functions as a Bootstrap carousel. You are welcome to just go straight to the code here, or keep reading to learn and understand how the code works.

Recently, I worked on a project that required an image gallery. It allowed the end-user to see everything the gallery had to show and, if the user wanted to see a larger version of a particular image, a modal pop-up displayed where the user could browse from one picture to the next, just like the popular Bootstrap carousel. While I was figuring out the best way to do this, I traversed across a multitude of webistes showcasing examples and even js-libraries. As I am sure you are in the same frame-of-mind now, as I was then, you don’t want to have to spend a bunch of time learning a new framework, library, or understanding someone else’s complex and eloquently entangled code concotion. Inevitably, the following code is something that I created that makes it SUPER EASY for someone to quickly utilize in their own projects.

 

At a Glance

Use the Code Now
Understand the Code

 

Use the Code Now

(Full Code Here)

 
To get your code working quickly you must complete two tasks:

 

1) Replace the images in the ‘#imagesList’ div with the images you want to display.

	<div id="imagesList" hidden>
		<img src="yourImagesHere1.jpg" class="img-responsive">
		<img src="yourImagesHere2.jpg" class="img-responsive">
		<img src="yourImagesHere3.jpg" class="img-responsive">
		<img src="yourImagesHere4.jpg" class="img-responsive">
		<img src="yourImagesHere5.jpg" class="img-responsive">
		<img src="yourImagesHere6.jpg" class="img-responsive">
	</div>

 

2) Replace the images in the divs with the id’s ‘#imageRow1’ and ‘#imageRow2’.

	<div class="row" id="imageRow1">
		<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
			<a onclick="showImageGallery(0)">
				<img src="yourImagesHere1.jpg" class="img-responsive">
			</a>
		</div>
		<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
			<a onclick="showImageGallery(1)">
				<img src="yourImagesHere2.jpg" class="img-responsive">
			</a>
		</div>
		<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
			<a onclick="showImageGallery(2)">
				<img src="yourImagesHere3.jpg" class="img-responsive">
			</a>
		</div>
	</div>

*Note: Make sure that the image order in the ‘#imagesList’ is the same as those in the ‘#imageRows’

 

Understand the Code

 

Sections

HTML
Javascript

 

The HTML

 

The Layout

The Hidden Images Div
The Modal
The Image Gallery

 

The Hidden Images Div

Here, we will create a hidden div with the id, ‘imagesList’. Inside of this div, we will place in all of the images that we want to display in the modal pop-up window.

	<div id="imagesList" hidden>
		<img src="yourImagesHere1.jpg" class="img-responsive">
		<img src="yourImagesHere2.jpg" class="img-responsive">
		<img src="yourImagesHere3.jpg" class="img-responsive">
		<img src="yourImagesHere4.jpg" class="img-responsive">
		<img src="yourImagesHere5.jpg" class="img-responsive">
		<img src="yourImagesHere6.jpg" class="img-responsive">
	</div>

The important thing to note here is that the images need to be in the same order as the images are displayed in the ‘gallery’ section we will create shortly. You will see that the images that I have used for this example end with a number, this is done for clarity and to help illustrate the image order. You DO NOT have to place a number at the end of all the images you are working with.

The other item to make note of that the ‘imagesList’ div item has the ‘property. This is to prevent the images from displaying. The purpose of the div is to simply serve as an array of sorts, where we will grab each image element by an index number.

 

The Modal

The code here is a simpe modal template. The main area of focus is the ‘.modal-content’ class, the ‘.modal-header’ class, and the ‘.modal-body’ class.

The ‘.modal-content’ holds everything that you want to have shown in your modal window. This includes the ‘modal-header’ and the ‘modal-body’.

The ‘modal-header’ here holds the ‘close’ modal button, which literally just closes the modal window. In addition, you can add an image title, quote, or whatever creative comes to mind.

The ‘modal-body’ is what holds all of the interesting bits, the next and previous functions, and a hidden ‘currentImageNumber’ paragraph element. The ‘currentImageNumber’ element will hold the current image’s index in the ‘imagesList’ div we created earlier. According to which function is selected, the next or previous function with add or subtract this value by one, which in turn will be used to display the correlating image.

	<div id="imageModal" class="modal fade" role="dialog">
		<div class="modal-dialog">	
		    <div class="modal-content">
		    	<div class="modal-header">
				    <button type="button" class="close" data-dismiss="modal">
				    	<span class="glyphicon glyphicon-remove"></span>
				    </button>
		      	</div>
		        <div class="modal-body">
		      		<span id="previousImage" class="glyphicon glyphicon-menu-left" onclick="previousImage()"></span>
		      		<span id="nextImage" class="glyphicon glyphicon-menu-right" onclick="nextImage()"></span>
		      		<p id="currentImageNumber" hidden>number</p>
		        </div>
		    </div>
		</div>
	</div>

*Note: The location of where you put your modal matters. In this example, I placed the modal code just under the ‘div.container’ element, that way, the amount of screen-space that the modal takes up will be based off the percentage of the ‘div.container’. If, for example, you were to put the modal code in a smaller HTML element, then the modal would display according to a percentage of that element, which could undesirable or too small for the end-user to look at or interpret.
In addition, you do not have to change or alter any of the code in this section. It will work as is.

 

The Image Gallery

The overall layout of the image gallery is a standard Bootstrap 3-column arrangment. Each column will hold an image in the image gallery. You will notice that each image is wrapped in an anchor tag with a function called, ‘showImageGallery’ and that function has a number parameter. This number represents that particular image’s index in the ‘imagesList’ div. For example, you can see below that the first image in the ‘imageRow1’ has the number parameter ‘0’ in the ‘showImageGallery’ function. If we look back to the ‘imagesList’ div, then we can see that the first image in our list (or image array) is ‘DefaultImage1.jpg’, which would be at the 0 index. See the pattern?

	<div class="row">
		<div class="row" id="imageRow1">
			<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
				<a onclick="showImageGallery(0)">
					<img src="DefaultImage1.jpg" class="img-responsive">
				</a>
			</div>
			<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
				<a onclick="showImageGallery(1)">
					<img src="DefaultImage2.jpg" class="img-responsive">
				</a>
			</div>
			<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
				<a onclick="showImageGallery(2)">
					<img src="DefaultImage3.jpg" class="img-responsive">
				</a>
			</div>
		</div>
	</div>

 

The Javascript Code

The JavaScript code can be broken down into four sections:

The Page Variables
The Show Gallery Function
The Next Image Function
The Previous Image Function

 

The Page Variables

There are two variables that we will be able to access throughout our script and use in our functions. The first variable is the ‘imagesList’. This holds our hidden div that stores all of our modal images. The second variable is the ‘imagesListLength’. This will let us know how many pictures we have in total and will be used in our ‘nextImage’ and ‘previousImage’ functions.

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

 

The Show Gallery Function

The showGallery function has four main components.

The first component will remove any previously appended html image elements from the modal. This way, we do not show more than one image at the same time in the modal.

The second component will display the model window. We first select the modal with JQuery, then use the Bootstrap method ‘.modal()’ with the word ‘show’ as a parameter to display the modal.

The third component will grab the desired image from the ‘imagesList’ div that we created in our HTML earlier. This is done in two parts, the first getting the image, and the second appending the image to the modal.

 

To acquire the image, we will use the JQuery method ‘children()’, which returns all of the image elements in an array. Next, to get the image that we want, we will grab it by its index number which was already provided earlier in our parameter (this would be the number provided inside the ‘onclick=”showImageGallery(1)’ click event. We then set all of that to a variable named, ‘image’.

 

The append the image to the modal, we will utilize a JQuery selector with the ‘image’ variable we just created. We then attach a JQuery method called ‘clone()’ (this just duplicates the selecte image element). Once we have that, we append the image to the modal.

	var showImageGallery = function(imageNumber){

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

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

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

	}

 

The Next Image Function

The nextImage function is made up of three parts.

The first part we have seen previously in the ‘showGallery’ method where we remove any previously existing images within the modal.

In the second part, we will grab the previous ‘currentImageNumber’ paragraph element value, check to see if that value is equal to ‘imagesListLength’ variable (the total number of images we have) that we created earlier, and then append the updated ‘currentImageNumber’ value by adding by one.

 

When we grab the ‘currentImageNumber’ value, we will use its id as our JQuery selector, get the text value by using the JQuery ‘text()’ method, and then use the parseInt() method to turn that value into an integer number. All of this is set to a variable named ‘nextNum’.

 

Now we check the value of the ‘nextNum’ variable. If the variable is equal or highest image index number, provided by the ‘imagesListLength’ variable, then we will reset the index to -1 since on the next line we will increase that value by one.

 

Finally, to complete the second part of the method, we will set the text value of the ‘currentImageNumber’ hidden paragraph element by using the ‘text()’ method again and adding in our ‘nextNum’ variable plus one. What this essentially does, is reset the currently viewed image back to the one at the beginning of the ‘imagesList’.

The third part of the nextImage function, appending a new image to the modal, is done the same way as the ‘showGallery’ function, except that we use ‘nextNum+1’ as our index parameter.

	var nextImage = function(){

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

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

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

	}

 

The Previous Image Function

The ‘previousImage’ method works in nearly the same aspect as the ‘nextImage’ function does except there is one main difference, we test to if the ‘currentImageNum’ is equal to zero. If it does equal zero, then we do not have any images at a negative index to display, so we will get the image at our highest image index and set that as our updated image.

 

The Full Code

	<!DOCTYPE html>
	<html lang="en">
		<head>
			<meta charset="UTF-8">
			<title>Easy Bootstrap Gallery with Pop-up Modal Carousel</title>
		</head>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	<body>

	<div id="imagesList" hidden>
		<img src="DefaultImage1.jpg" class="img-responsive">
		<img src="DefaultImage2.jpg" class="img-responsive">
		<img src="DefaultImage3.jpg" class="img-responsive">
		<img src="DefaultImage4.jpg" class="img-responsive">
		<img src="DefaultImage5.jpg" class="img-responsive">
		<img src="DefaultImage6.jpg" class="img-responsive">
	</div>

	<div class="container">
		<div id="imageModal" class="modal fade" role="dialog">
			<div class="modal-dialog">	
			    <div class="modal-content">
			    	<div class="modal-header">
					    <button type="button" class="close" data-dismiss="modal">
					    	<span class="glyphicon glyphicon-remove"></span>
					    </button>
			      	</div>
			        <div class="modal-body">
			      		<span id="previousImage" class="glyphicon glyphicon-menu-left" onclick="previousImage()"></span>
			      		<span id="nextImage" class="glyphicon glyphicon-menu-right" onclick="nextImage()"></span>
			      		<p id="currentImageNumber" hidden>number</p>
			        </div>
			    </div>
			</div>
		</div>
		<div class="row">
			<div class="row" id="imageRow1">
				<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
					<a onclick="showImageGallery(0)">
						<img src="DefaultImage1.jpg" class="img-responsive">
					</a>
				</div>
				<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
					<a onclick="showImageGallery(1)">
						<img src="DefaultImage2.jpg" class="img-responsive">
					</a>
				</div>
				<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
					<a onclick="showImageGallery(2)">
						<img src="DefaultImage3.jpg" class="img-responsive">
					</a>
				</div>
			</div>
			<br>
			<div class="row" id="imageRow2">
				<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
					<a onclick="showImageGallery(3)">
						<img src="DefaultImage4.jpg" class="img-responsive">
					</a>
				</div>
				<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
					<a onclick="showImageGallery(4)">
						<img src="DefaultImage5.jpg" class="img-responsive">
					</a>
				</div>
				<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
					<a onclick="showImageGallery(5)">
						<img src="DefaultImage6.jpg" class="img-responsive">
					</a>
				</div>
			</div>
		</div>
	</div>
	<script>

		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');

		}

	</script>
	</body>
	</html>