Skip to main content

Command Palette

Search for a command to run...

Simple JavaScript Tutorial for Building an Image Gallery

Published
•5 min read•View as Markdown
Simple JavaScript Tutorial for Building an Image Gallery
J

Hey! I’m a second-year BTech student in Information Technology at a Tier-3 college under AKTU. Right now, I’m working on building myself to secure an irreplaceable place in the tech industry. I’m someone who loves diving deep into details, pondering over problems I can solve, and exploring different realms of reality.This space is where I will document my journey!

After breaking my pact with procrastination here I am with another article! This one is all about integrating the aspect of websites that provides functionality. Crossing the static HTML & CSS, javascript is about adding life to those pages by aligning it with logic and creating dynamically updating content, control multimedia and animated images. I am starting to add that liveliness by implementing a simple image gallery, after conquering those flat must do’s, so come along!

The setup

This mini project is divided into three segments: HTML file to provide the structure, CSS file for basic styling and Js to put it all together. The HTML and CSS segments are provided in the MDN challenge along with the necessary steps. Thereby, I’ll primarily discuss the latter.

In short the HTML consists of a simple div having an image, another div on top of it and a button. A thumbar situation at the bottom of all of it. Somewhat like this:

<h1>Image gallery </h1>
<div class="full-img">
  <img
    class="displayed-img"
    src="pic1.jpg"
    alt="Closeup of a human eye" />
  <div class="overlay"></div>
  <button class="dark">Darken</button>
</div>
<div class="thumb-bar"></div>

The CSS file consists of the full lengthed image in a relative position to itself, then the div above it of class overlay positioned absolute to its parent, full lengthed div and a button placed at the top-left. All accompanied by a thumbar at the bottom in display set as flex. To actually style the button and the thumbar when they are accessed by cursor and tab from mouse users,keyboard users respectively, pseudo classes such as hover and focus are used. This is implemented as:

button:hover,
button:focus {
  color: rgb(150 150 150 / 1);
  background-color: black;
}
.thumb-bar img:hover,
.thumb-bar img:focus {
  outline: 2px solid black;
}

In the JavaScript file:

  • To begin with, MDN has provided variables of elements selected using CSS selectors via document method querySelector().

  • Then I made an array of objects called images having the filename and alternative text (alt) in each one. This would help us to iterate over them.

  • A baseURL based on where the images are stored on your system, as it is a small project.

  • Then comes the intriguing part, a for of loop to:

    → Create a new element ‘img’ in every iteration and assign its alternative text and

    source as per the amalgamation of baseURL and the filename.

    → Setting ‘tabindex’ attribute to the images, so that they are accessible to keyboard users. Also, appending each image to the thumbar at the bottom.

    → Adding two event listeners, one satisfying the ‘click’ event. Whenever the user clicks the image on the thumbar, a full sized image appears. This is done by updating the contents of dispalyedImage.

    → Adding another event listener that satisfies the ‘keydown’ event. Whenever the user presses Enter on the keyboard, they experience a full sized image on the screen.

      pic.addEventListener('click',()=> {
      updateDisplayedImage(pic); });
      pic.addEventListener("keydown",(e)=> {
      if(e.key=='Enter') {
        updateDisplayedImage(e.currentTarget); });
    
    • The button on the top-left is supposed to toggle the image between dark and light effects. This is done by a basic if condition, checking if the classList conatins ‘dark’ or not. Then, changing the button’s content and the effect accordingly. Updation of the opacity value of the overlay div, we placed on top of the image form 0 to 0.5 leads to this result.

A Few Enhancements:

  1. Added an image counter at the bottom-right of the main image.

    → This includes a basic div positioned absolutely on the image with some minimal styling.

    → A function in Js to rewrite the textContent of the div everytime the function is called.

    → Called the function in both the above mentioned events with the current index as the parameter.

  2. Added more keydown events like ‘ArrowRight’ and ‘ArrowLeft’ to access the next and previous images respectively thereby, enchancing the accessibility of the gallery.

    → This is done by firstly calculating the indices of the previous image by cur=(cur- 1)%images.length and the next image by cur=(cur+1)%images.length.

    → As per the index, the repective filename and alternative text is then passed as a variable in the updateDisplayedImage funciton.

    →The function then updates the full sized image on the screen.

    → To cover an egde case in the ArrowLeft key, when cur=0, I assigned it to the length of the array therby making a full circle of access. The handling of the left arrow key event looks somewhat like this:

     if(e.key==='ArrowLeft')
     { e.preventDefault();
       if(cur==0)  {
         cur=images.length-1;}
       else{
       cur=(cur-1)%images.length;}
       k.src=`${baseURL}/${images[cur].filename}.jpg`;
       k.alt=images[cur].alt;
       count(cur+1);
       updateDisplayedImage(k);  }
    

Comprehensive Summary

So, to sum it all up these are all the features I tried. You can definetly take this one step futher by adding things like:

  • Adding light and dark themed modes, changing the text and background color as needed then.

  • A slideshow button, where each picture shows for about 2-3 seconds and then instantly goes to another image.

  • Adding different colored overlays on top of the image controlled by a radio button.

    The opportunities are truly endless!

That was all about my little adventure in trying and implementing something with JavaScript. I hope that you learned something meaningful. I have listed almost everything here but if needed, you can access the full version from my github. In the next article, I will probably be scaling up on the complexity ladder with another mini-project.

Hoping to see you in the next one!

~JasDoIt