In this article we are going to build a simple random-imge-generator library with javascript .We are going to build this whole library from scratch without relying on jquery or any other library , let’s do this .

The outcome

library in action

To keep to tutorial simple we won’t be adding too many features it will contain only a javascript file and a html file with some styling in it .

Designing the library

Before we start developing the library let’s take a look at how people will use it . Making the design of library actually helps makes the development part easier later on.

Devs who will use it will need to have some html button tags for next button , prev button and img tag for showing up random images .

These tags have some classes which we will pass in our library for proper functioning .

<body>
    <center>
        <div id="image">
            <img id = "random_image" src="" alt="">
        </div>
        <div class="buttons">
            <div class="button_prev btn btn-primary">Prev</div>
            <div class="button_next btn btn-success">Next</div>
        </div>
    </center>
</body>

Styling all these tags with css using css class and id selector

<style>
    #image{
        margin: 100px auto 30px auto;
        width:500px;
        height:300px;
        border:2px solid black;
        border-radius: 10px;
        position:relative;
        overflow: hidden;
    }
    #image img{
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        object-fit: cover;
    }
    .buttons{
        width:500px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
</style>

people are free to style these tags according to their need .It’s important , however , that div of next button and prev button have unique classes which will passed in library for functioning of next and prev button .

There must be an img tag for showing up random images with an unique class . In the above code we are using random_image as an unique class for img tag .

After setting up the markup , now we need to include our library in our html file and initialize it .

<script src="index.js"></script>
<script>
    randomImageGen.init('random_image','button_next','button_prev','nature');
</script>

Including the index.js file will make the randomImageGen object globally avaialble . This object have only one method which is accepting four parameters . In this way we can have multiple random image gallary in one page .

We are sending four parameters while initializing our library . Here is the classification of parameters

  • First parameter is the unique class of img tag in which random image will be shown
  • Second parameter is the unique class of next button which will change the image to next.
  • Third parameter is the unique class of prev button which will show the previous image in img tag.
  • Last and fourth parameter is about the topic of random image . It accepts a word i.e., ‘nature’ in above code , people can choose ‘cats’ , ‘animals’ etc.

Developing the library

When we are building front-end javascript library we need to make sure we register their API properly , there are many ways to do this . The simplest and easy way is shown below which is proposed by Jordan Checkman .

(function(window) {
  function define_library() {
    // Create the library object and all its properties and methods.
    var randomImageGen = {};
    randomImageGen.init = function(img_tag_id,next_btn_class,prev_btn_class,topic) {
      // Our library's logic goes here.
    }
    return randomImageGen ;
  }

  // Add the randomImageGen object to global scope if its not already defined.
  if(typeof(randomImageGen) === 'undefined') {
    window.randomImageGen = define_library();
  }
  else{
    console.log("Library already defined.");
  }
})(window);

The above code is wrapped in a self executing javascript function . As soon as the user add the index.js to html file the library will register automatically and randomImageGen object with all it’s methods will be made available to user.

Our library has only one method randomImageGen.init(img_tag_id,next_btn_class,prev_btn_class,topic) which selects the DOM element and add some event listeners to it .

First we need to select all the DOM elements with the help of id’s and classes , we can’t use jquery so we have to rely on vanilla javascript methods for handling DOM .

We will use unsplash API to fetch random images , when DOM loads then we have to call fetch API and render the recieved image in image tag.

 var image = document.querySelector('#'+img_tag_id);
 var prev = document.querySelector('.'+prev_btn_class);
 var next = document.querySelector('.'+next_btn_class);
 var secptr = -1;
 var images = [];


 fetch(`https://source.unsplash.com/1600x900/?${topic}`).then(response => {
    images.push(response.url);
    image.src = response.url;
    secptr++;
    checkClass(secptr);
 })

We have used a pointer secptr and it’s default value is set to -1 , whenever an images is fetched then it’s source is pushed in a list i.e., images and secptr is incremented by 1 .

We have called a function i.e., checkClass(secptr) . This function will check if the value of secptr is 0 or -1 then it will disable the prev button by adding disable class to it ,and it means the user is at the last image and cannot go prev further.

Note : Don’t forgot to include bootstrap.min.css cause disable class comes from bootstrap css file .

The body of checkClass(secptr) function is as follows , we have callled this method once when the DOM loads .

function checkClass(secptr){
   if(secptr == 0 || secptr == -1){
      prev.classList.add("disabled");
   }else{
      prev.classList.remove("disabled");
   }
 }

 checkClass(secptr);

I think article is going longer , I will post the further remaining methods in next article

You can follow me on Linkedin : Anand Raj

Don’t forget to follow our Linkedin page for latest updates : BePractical

Next Article : https://bepractical.tech/how-to-build-your-own-library-with-vanilla-javascript-part-2/

Thank you for reading ✌