How to: Build a Modal Class in Vanilla JavaScript using Object Orientation

Trae Coker
8 min readOct 12, 2021

--

As a beginner developer learning vanilla JavaScript it can be daunting at first to fathom the possibilities of the world’s most popular programming language. In this tutorial I aim to show how we can utilize Object Orientation in JavaScript to give some character to a SPA (Single Page Application). My hope is that we will learn more about classes and the benefits of Object Orientation along the way.

As an example we are going to utilize a philosophy-Hub type app I recently built called SOPHIA. Sophia will let our users create a customer pantheon of philosophers from across the ages that they wish to learn from. So deep, I know…

“I cannot teach anybody anything, I can only make them think.” — Socrates

First, why use a modal? In JavaScript there are many ways to accomplish the same tasks, and this is only one route one might choose to go down. We are building a Single Page Application in this example because it is a great way to get to know what JavaScript is capable of as a front-end language.

This means we want to be able to have access to all of our CRUD functions without ever leaving the current page. Using CSS and JavaScript to create a modal will give our one and only page more depth by allowing us to open and close “windows” for things like forms and displays. Pretty neat!

Front-end web programming has three essential pillars:

1. Manipulating the Document Object Model (DOM)
2. Recognizing JS events
3. Communicating with the server

All three of these pillars will feature in this tutorial and are what makes a Single Page Application possible in the first place.

A quick note on Object Orientation:
OO is not essential for writing code, but it is a powerful and efficient design strategy that abstracts our code making it easier to change, better at controlling data, easier to replicate, and easier to understand. For a deeper dive, check this article out.

With our foundation set, let’s build…

Front-end file structure example.

We start by building out the architecture of our front end using Object Oriented conventions: Our main folder contains an index.html, index.js, and style.css files with a subfolder with separate files for each of our classes and their corresponding API service calls.

We separate our API calls from our object classes to keep our communication with the server separate from the functionality of the objects we create from communicating with the server.

Pantheon class vs Pantheon API service class. The API service class fetch’s the data that the other class uses to create Pantheon objects with.

The CSS we will use for this example comes from this resource over at w3schools.com. Go ahead and copy this CSS into your style.css file. This will give us a basic starting point for our modal that you are welcome to customize later.

CSS properties for moda, modal-content, close, and close:hover

Next, add this HTML into the body of your index.HTML file. This is the target div that we will be operating on.

Now, we create a modal.js file where our modal class will live, and give it the basic class declaration.

Syntax for creating a new class

Start by building two ‘get’ functions. Getter methods allow us to return a calculated value as though it were an object property and we will use them here to return different parts of our modal for operating on.

The first function ‘get modal’ will return the entire parent div by querying for “#myModal”. The second function ‘get main’ will return the inner div that we will want to do most of our appending to by querying for the id “modal-main”.

Next we will create a modal variable that will let us access these methods from anywhere in our application. Hop on over to index.js and add
“const modal = new Modal();”.

We set the modal variable to equal a new instance of our Modal class and now by calling “modal” we have access to the functions we are building in the Modal class!

To test this out you can open your index.HTML page in the browser, open your console and type modal.modal and modal.main. We see that it returns to us the divs that we queried for in the last step.

Going back to our modal class, we will now build out functions that we can call to open and close our modal.

If we take a look at our CSS properties that we pasted in we can see that the default display for our modal is set to “none”.

You may have noticed if you looked at your index.HTML that nothing shows up yet. This is good. We want our modal to be hidden by default as it will allow us to operate on it behind the scenes based upon our user interactions and utilize this one div for several different features.

Our open function will set the display from the default “none” to “block” making it appear on the screen. Close will do the opposite and set the display from “block” back to “none”.

Notice the word ‘this’ in both of these functions. ‘This’ can be a challenging concept to grasp in JavaScript, but an important one to understand. Here our keyword ‘this’ is referring to the modal object calling the function (for us it will be the modal variable we declared in index.js). by calling “this.modal.style” we are calling the object and then calling our “get modal” function that we defined in the previous step to grab our parent div to operate on.

Once again we can check this in our browser by refreshing our page and typing “modal.open()” in our console.

Modal pops-up but contains no content

Not much to look at quite yet, but we can see it is popping up our modal window on screen. Typing “modal.close()” should remove the window.

modal returns to hidden style with modal.close()

We want our user to be able to close this pop-up window by either clicking the X in the top right corner or by clicking anywhere off the window. We are going to reference this functionality first in our constructor method.

A constructor method should be the first method in your class

Constructor methods are ways of programming what properties all objects will have upon instantiation. Thus by adding the closing event listener to our constructor function we ensure this functionality comes built into our modal variable that we are declaring with a new Modal object in index.js.

Lastly for our modal class we will build out the close event listener that we referenced in the last step.

|| means “or” in JavaScript and will call this.close() if either of these conditions are met

Once again we are utilizing “this” and calling the modal getter we made earlier to and the event to our parent div. We use || to give us an “or” conditional to allow both a close if the X is clicked or the user clicks off of our modal. (note that the id “my modal” is the parent of the “modal-main” div. “modal-main” is the actual window that pops up, while “my modal” is the blacked out screen behind it.)

Simple as that; Our modal class is now fully functional and ready for implementation.

We can use our modal to display objects that we have acquired and rendered via fetch requests to a database:

Setting modal.main.innerText = “” assures that we clear any existing data appended to the modal before we append our selected philosopher element

Modals are a great way to implement forms on a single page application. It looks nice, it keeps your form separate from the rest of your content, and it allows you to capture and send data to a database while only re-rendering the data being displayed if you need to.

innerHTML allows us to fill in our modal.main div with a complete form worth of HTML

Simply change modal.main.innerHTML to whatever form or content you desire. Render the content, add event listeners, append whatever nodes you need to, and finish of your functions by calling “modal.open()”.

How the form looks once rendered

Your modal will close with the X button or clicking off, or if you need it to close based on a certain interaction between the user and your context, ex: clicking submit on a form, no problem, simply use “modal.close()” on whatever call back function is listening on said event.

Our createPantheon fetch request will close our modal only if our request does not return any errors

Mission Accomplished!

Being able to manipulate the DOM in this way, listening for user events, triggering functions based on said events, and communicating with a server without the need to refresh a page are what makes JavaScript powerful and expressive.

Combining this with Object Orientation design patterns allows us to file away our data and functionality neatly into their own “cells” so they can communicate more effectively and efficiently with the other cells that make up the organism that is our software.

Raphael’s famous “School of Athens” painting depicting many famous philosophers interacting with one another

I hope this tutorial taught you a cool new feature that you can build into your own vanilla JavaScript projects, and I hope it gave you some helpful insights along the way!

What cool features have you implemented with JavaScript using Object Orientation?

--

--

Trae Coker
Trae Coker

Written by Trae Coker

Music, Code, Alchemy. Transmuting ideas into form. Perpetually in awe of the human experience.

No responses yet