DEV Community

Anurag Gupta
Anurag Gupta

Posted on

Craft Your Own Unique Modal (Popups) with HTML, CSS, and JavaScript!

Welcome to the world of web applications, where popups play a crucial role in enhancing user experiences and enabling dynamic interactions. You've probably encountered popups while navigating through websites, whether it's a handy confirmation prompt before committing to action or seamlessly gathering user input on the go. Have you ever wondered how these versatile popups come to life, effortlessly appearing on the screen to fulfil diverse requirements?

In this captivating article, we'll unravel the secrets behind creating custom popups and empower you to tailor them to your heart's content. Brace yourself to embark on an exciting journey through the realms of HTML, CSS, and JavaScript, as we guide you step-by-step in constructing your very own personalized popups. Say goodbye to generic and limited solutions – with our expert guidance, you'll gain the freedom to craft unique popups that seamlessly integrate into any corner of the web. So, let's dive in and unlock the limitless potential of HTML, CSS, and JavaScript for your popup creations!

Custom Modal using HTML, CSS and JavaScript

Prerequisites

  • πŸ’‘ Basic understanding of HTML, CSS and JavaScript.
  • πŸ“ Editor or IDE for your code.

How to create a custom modal?

Let's jump right in and explore the exciting realm of custom popups without any delay!

Note: For the purpose of this tutorial, I'll demonstrate keeping everything in a single file. However, feel free to separate your CSS and JavaScript code into individual files as per your preference.

Step 1:

To begin, we'll craft an HTML file called custom-popup.html and include the essential structure needed for our custom modal.



<!DOCTYPE html>
<html>
    <head>
        <title>Custom Modal using HTML, CSS and JavaScript</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    </head>
    <body>
        <h1>Custom Modal using HTML, CSS and JavaScript</h1>
    </body>
</html>


Enter fullscreen mode Exit fullscreen mode

The above HTML code will generate an output that resembles the following screen:

Basic Structure of HTML

Step 2:

Now, let's proceed to write the HTML code for our modal window.

Structure of Modal
To create our modal, we'll encapsulate the code within a wrapper that overlays the entire screen, accompanied by a semi-transparent background. This design not only ensures that the modal becomes the focal point but also prevents interaction with buttons or elements behind it. To achieve this, we'll follow the HTML structure outlined below for our modal design.



   body
   |- modal-wrapper 
      |- modal
         |- header
         |- body
         |- footer


Enter fullscreen mode Exit fullscreen mode

Once we've implemented the corresponding HTML structure, it will transform into the following appearance:



<!DOCTYPE html>
<html>
    <head>
        <title>Custom Modal using HTML, CSS and JavaScript</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    </head>
    <body>
        <h1>Custom Modal using HTML, CSS and JavaScript</h1>

        <!-- Modal HTML Code Start -->
        <div class="modal-wrapper">
            <div class="modal">
                <div class="modal-header">
                    Custom Modal
                    <span class="close-modal">x</span>
                </div>
                <div class="modal-body">
                    Do you want to save changes?
                </div>
                <div class="modal-footer">
                    <button class="action-btn">Yes</button>
                    <button class="cancel-btn">Cancel</button>
                </div>
            </div>
        </div>
        <!-- Modal HTML Code End -->

    </body>
</html>


Enter fullscreen mode Exit fullscreen mode

Step 3:

As you can observe, I have already included the class attribute in the HTML tag above to facilitate applying CSS styles later on. Now, let's proceed to apply CSS to our modal code and witness the delightful transformation it undergoes. Add below CSS code in <head> of html document within <style></style> tag to apply CSS.



body {
    font-family: Arial, Helvetica, sans-serif;
}
.modal-wrapper {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgb(15 15 15 / 30%);
}
.modal {
    border: 1px solid #ffffff;
    width: 40%;
    border-radius: 8px;
    margin: 12% auto;
    background: white;
    box-shadow: 3px 3px 3px #0000002e;
}
.modal-header {
    font-size: 18px;
    font-weight: bold;
    border-bottom: 1px solid #cfcfcf;
    padding: 15px 15px;
}
.modal-body {
    padding: 20px 15px;
    height: 80px;
}
.modal-footer {
    border-top: 1px solid #cfcfcf;
    padding: 15px 15px;
    text-align: right;
}
.modal-footer > button {
    width: 75px;
    height: 30px;
    border-radius: 3px;
    color: white;
    letter-spacing: 0.5px;
    font-weight: bold;
    cursor: pointer;
}
.action-btn {
    background: #2a9577;
    border: 1px solid #2a9577;
}
.cancel-btn {
    background: #d73c33;
    border: 1px solid #d73c33;
}
.close-modal {
    float: right;
    margin-right: 5px;
    font-weight: 300;
    cursor: pointer;
}


Enter fullscreen mode Exit fullscreen mode

Once the CSS is applied, your custom modal will undergo a remarkable transformation and take on a stunning appearance, resembling the following design:

Modal screen after applying CSS

Step 4:

With our design now in place, it's time to bring it to life. Modal windows, typically triggered by button clicks or other user actions, are initially hidden to ensure interactivity. To achieve this behavior, we'll add the CSS property display:none to the modal-wrapper class. Additionally, we'll create a button labeled "Open Modal" and position it after the <h1> heading. This button will serve as the catalyst for unveiling the captivating modal experience.

Now modal-wrapper class will look like below:



.modal-wrapper {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgb(15 15 15 / 30%);
    display: none;
}


Enter fullscreen mode Exit fullscreen mode

and after incorporating the new "Open Modal" button, our HTML code with its CSS will be enhanced and take on the following form:



<body>
    <h1>Custom Modal using HTML, CSS and JavaScript</h1>
    <p>Click below "Open Modal" button to open the Modal.</p>
    <button class="open-modal-btn">Open Modal</button>

    <!-- Modal HTML Code Start -->
    .....
</body>


Enter fullscreen mode Exit fullscreen mode

Make sure to add CSS for the button as well and add it in style tag. CSS for open-modal-btn class is below:



.open-modal-btn {
    border: none;
    width: 150px;
    height: 40px;
    background: #5783db;
    color: white;
    font-size: 16px;
    font-weight: bold;
    border-radius: 5px;
    cursor: pointer;
}


Enter fullscreen mode Exit fullscreen mode

After implementing all these modifications, the resulting screen will exhibit the following appearance:

Open Modal Button Implementation

Step 5:

Now, it's time to breathe life into our creation and make it fully functional.

To enable the dynamic behavior of our modal, we'll write a JavaScript function responsible for launching and closing it. By manipulating the CSS property of the modal-wrapper class, we can control its visibility. Setting display:block will reveal the modal, while display:none will hide it.

Let's implement this function and place it within the <script> tag in the body section, ensuring it appears after the closing tag of the modal HTML. This arrangement will enable the seamless integration of JavaScript functionality.

To accomplish this, we'll need to assign an id attribute to the modal-wrapper element. By doing so, we can dynamically access the style property of the element within our function. After adding this, it will look like below:



 <div class="modal-wrapper" id="#customModal">
 .....


Enter fullscreen mode Exit fullscreen mode

and JavaScript function to hide and show the modal within <script> tag:



const modalElement = document.getElementById('#customModal');
function handleModal(action) {
    modalElement.style.display = action ? 'block' : 'none';
}


Enter fullscreen mode Exit fullscreen mode

Let's break it down:



const modalElement = document.getElementById('#customModal');


Enter fullscreen mode Exit fullscreen mode

This line retrieves the DOM element with the id attribute set to "customModal" using the getElementById method. The reference to this element is stored in the modalElement variable.



function handleModal(action) { ... }


Enter fullscreen mode Exit fullscreen mode

This declares a function named handleModal that takes an action parameter.



modalElement.style.display = action ? 'block' : 'none';


Enter fullscreen mode Exit fullscreen mode

Within the handleModal function, this line dynamically modifies the display CSS property of the modalElement. If the action parameter is truthy, the display property is set to 'block', making the modal visible. Otherwise, if the action parameter is falsy, the display property is set to 'none', hiding the modal.

In summary, this code allows you to control the visibility of the modal element (modalElement) by calling the handleModal function and passing a boolean value. When the action parameter is true, the modal becomes visible, and when it is false, the modal is hidden.

Step 6:

In this final step, we will attach onclick event listeners to the respective buttons and call handleModal function with respective parameter, completing our implementation.

After implementing this step, the HTML code for our buttons will resemble the following:



.....

<button class="open-modal-btn" onclick="handleModal(1)">Open Modal</button>

.....

<div class="modal-header">
    Custom Modal
    <span class="close-modal" onclick="handleModal(0)">x</span>
</div>

.....

<button class="action-btn" onclick="alert('You clicked Yes.')">Yes</button>
<button class="cancel-btn" onclick="handleModal(0)">Cancel</button>

.....



Enter fullscreen mode Exit fullscreen mode

Congratulations! We have successfully completed all the necessary steps. Now, it's time to put our creation to the test. But before we do that, let's take a moment to review the overall code we have developed thus far:



<!DOCTYPE html>
<html>

<head>
    <title>Custom Modal using HTML, CSS and JavaScript</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <style>
        body {
            font-family: Arial, Helvetica, sans-serif;
        }
        .modal-wrapper {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgb(15 15 15 / 30%);
            display: none;
        }
        .modal {
            border: 1px solid #ffffff;
            width: 40%;
            border-radius: 8px;
            margin: 12% auto;
            background: white;
            box-shadow: 3px 3px 3px #0000002e;
        }
        .modal-header {
            font-size: 18px;
            font-weight: bold;
            border-bottom: 1px solid #cfcfcf;
            padding: 15px 15px;
        }
        .modal-body {
            padding: 20px 15px;
            height: 80px;
        }
        .modal-footer {
            border-top: 1px solid #cfcfcf;
            padding: 15px 15px;
            text-align: right;
        }
        .modal-footer>button {
            width: 75px;
            height: 30px;
            border-radius: 3px;
            color: white;
            letter-spacing: 0.5px;
            font-weight: bold;
            cursor: pointer;
        }
        .action-btn {
            background: #2a9577;
            border: 1px solid #2a9577;
        }
        .cancel-btn {
            background: #d73c33;
            border: 1px solid #d73c33;
        }
        .open-modal-btn {
            border: none;
            width: 150px;
            height: 40px;
            background: #5783db;
            color: white;
            font-size: 16px;
            font-weight: bold;
            border-radius: 5px;
            cursor: pointer;
        }
        .close-modal {
            float: right;
            margin-right: 5px;
            font-weight: 300;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <h1>Custom Modal using HTML, CSS and JavaScript</h1>
    <p>Click below "Open Modal" button to open the Modal.</p>
    <button class="open-modal-btn" onclick="handleModal(1)">Open Modal</button>

    <!-- Modal HTML Code Start -->
    <div class="modal-wrapper" id="#customModal">
        <div class="modal">
            <div class="modal-header">
                Custom Modal
                <span class="close-modal" onclick="handleModal(0)">x</span>
            </div>
            <div class="modal-body">
                Do you want to save changes?
            </div>
            <div class="modal-footer">
                <button class="action-btn" onclick="alert('You clicked Yes.')">Yes</button>
                <button class="cancel-btn" onclick="handleModal(0)">Cancel</button>
            </div>
        </div>
    </div>
    <!-- Modal HTML Code End -->

    <script type="text/javascript">
        const modalElement = document.getElementById('#customModal');
        function handleModal(action) {
            modalElement.style.display = action ? 'block' : 'none';
        }
    </script>
</body>

</html>


Enter fullscreen mode Exit fullscreen mode

Take a look at this animated GIF that demonstrates how our Custom Modal works in action:

Final Output

Conclusion

In conclusion, we have explored the process of creating a custom modal(popup) window using HTML, CSS, and JavaScript. From structuring the HTML and styling the modal to implementing dynamic functionality, we have gained insights into crafting engaging and interactive user experiences. With this knowledge, you can now unleash your creativity and seamlessly integrate custom modals into your web applications.


Thanks for reading this article. If you found this article helpful, I would greatly appreciate your support! Feel free to show your appreciation by liking, subscribing, and sharing your thoughts in the comments section below 😊

Happy coding!

Top comments (2)

Collapse
 
anshu7977 profile image
Anshu7977

Incredible work! I love how it beautifully demonstrates the potential of combining html/css/js to build complex components without too much code. We often rely on libraries for quick iterations but personalization adds an unparalleled level of control and creativity. Kudos πŸ‘

Collapse
 
officialanurag profile image
Anurag Gupta

Thanks @anshu7977 ☺️