Creating Simple Image Gallery Part 2

In part 1 we have created image gallery and in this post we will bring it to the end by adding interactivity. So now when ever we click on the thumbnail image, it’s full version has to be shown on the right column. For this purpose we will need a little Javascript.

But don’t worry too much about Javascript we will be using jquery for the most part, as its usage is familiar and easier to make DOM selections.

Adding interaction to our Image Gallery

Currently we have following status of image gallery.

See the Pen fBxEH by Samiullah Khan (@samiullah1989) on CodePen.6143

Let’s add the Behavior Part

Step 1:

First of all Let’s trigger a click event whenever images inside thumb div is Clicked


We have other counter parts like bind, click methods but the “on” is recommended one because it can also be triggered on the DOM nodes that are dynamically created.

Next we want to highlight the current Image by adding a red border around it.


So in above code snippet, clicking on thumbnail image will remove the class “in” from all of it’s siblings DOM nodes. The second line would add a class “in” to current element. ( addClass would take care duplicate classes ).

highlighting current img in image gallery

Now we have arrived to the tricky how we gonna swap out the source of the image in full image section. For the sake for this demo we’ve used image from lorem pixlel and it’s url structure look like this

The 150/150 are the height and width of the image and letter 1 at the end is the unique id for an image. So in this case we are changing the Width and height dynamically.

 $el = $(this).attr('src');
 $elLastIndex = $el.length-1;
 $elValue = $el.substr($elLastIndex,1);
 $('.full img').attr('src',''+$elValue);
  1. On line 4: We are taking Source of current image.
  2. On line 5-6: We are taking the last unique number.
  3. On line 7:  Changing src tag of a full image.


Final Result

See the Pen Creating Image Gallery Part 2 by Samiullah Khan (@samiullah1989) on CodePen.6143

That’s all we have for this time around. We have successfully created an Image Gallery. I hope you people enjoyed it. Kindly share you thoughts and let me know how this can be further improved.




Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.