Skip to main content

Creating custom modal using HTML, CSS and Vanilla Javascript

Create custom modal using pure javascript and css. You can copy the javascript and css mentioned below. Comments are added for documentation purpose only.
The modal can also be closed using the Esc key.

HTML:-

<a data-custom-modal="#modal">Modal</a>
<div class="custom-modal" id="modal">
        <div class="custom-modal-body">
                <div class="header">
                    <h2 class="heading">Modal Heading<a class="close">&times;</a></h2>
                </div>
                <div class="body">
                    Modal Body
                </div>
                <div class="custom-modal-footer">
                    Modal Footer
                </div>
         </div>
</div>


CSS:-

.custom-modal{
    position: fixed;
    visibility: hidden;
    overflow-y: auto;
    background: rgba(0, 0, 0, 0.6);
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 999999;
    opacity: 0;
    transition: opacity 0.125s 0s ease;
    transition-property: all;
}
.custom-modal>.custom-modal-body{
    width: 65%;
    background: rgba(255, 255, 255, 1);
    margin: 2vw auto;
    padding: 2vw;
    text-align: center;
    border-radius: 0.85vw;
}
.custom-modal>.custom-modal-body>.body{
    text-align: left;
    line-height: 120%;
}
.custom-modal>.custom-modal-body>.custom-modal-footer{
    text-align: right;
}
.custom-modal>.custom-modal-body>.custom-modal-footer, .custom-modal>.custom-modal-body>.body{
    border-top: 2px solid #EEE;
    margin: 0;
    padding: 0;
}
.custom-modal>.custom-modal-body>.header>.heading>.close{
    position: relative;
    top: -3vw;
    right: 0vw;
    opacity: 0.35;
    float: right;
}
.custom-modal>.custom-modal-body>.header>.heading>.close:hover{
    opacity: 1;
}


Javascript:-

/**
 * This function shows the appropriate modal after the handler is being clicked.
 * @param {Selector} element The handler which is being clicked.
 */
function modal(element) {
    /**
     * This will check whether the parameter is a string telling the modal to show or the object from which the string will be fetched.
     */
    if (typeof element === "object") {
        element = element.getAttribute("data-custom-modal");
    }
    setSelector();
    var e = $(element);
    e.style.opacity = e.style.opacity == 0 ? 1 : 0;
    e.style.visibility = e.style.visibility == "visible" ? "hidden" : "visible";
    shown = !shown;
    document.getElementsByTagName("body")[0].style.overflowY = shown == true ? "hidden" : "auto";
    document.onkeypress = function (event) {
        /**
         * This will exit the modal when the Escape key is pressed
         */
        if (event.keyCode == 27 && shown == true) {
            $(element + " .close").click();
        }
    };
    try {
        var a = $_("a[data-custom-modal]");
        for (var i = 0; i < a.length; i++) {
            a[i].onclick = function (e) {
                e.preventDefault();
                if (shown == true) {
                    $(element + " .close").click();
                }
                modal(this);
            };
        }
    } catch (ex) {
    }
    $(element + " .close").onclick = function (ev) {
        ev.preventDefault();
        e.style.opacity = e.style.opacity == 0 ? 1 : 0;
        e.style.visibility = e.style.visibility == "visible" ? "hidden" : "visible";
        shown = !shown;
        document.getElementsByTagName("body")[0].style.overflowY = shown == true ? "hidden" : "auto";
    };
}

/**
 * This function sets the <strong>$</strong> as the querySelector and <strong>$_</strong> as the querySelectorAll
 */
function setSelector() {
    /**
     * This statement sets the <strong>$</strong> as the querySelector
     * @param {String} selector The handler of the element(s)
     * @returns {Element}
     */
    window.$ = function (selector) {
        return document.querySelector(selector);
    };
    /**
     * This statement sets the <strong>$_</strong> as the querySelectorAll
     * @param {String} selector The handler of the element(s)
     * @returns {Element}
     */
    window.$_ = function (selector) {
        return document.querySelectorAll(selector);
    };
}

Comments

Popular posts from this blog

WP similar or related posts widget without using any plugin

Hi guys, Recently I was working on some WP website and my client told me that he required a widget for displaying related/similar posts on the single post page. But as his website was already using many plugins, even for some pretty small tasks like this one, I decided not to use another WP plugin (plugins are not good for your WP websites, we will discuss about that on some other post.) I am not explaining the code as it is pretty simple if you are familiar with WP classes. But please let me know if you have any questions related to the PHP code posted below in the comments section or even much better, on Gist. You can add the following code directly in your child theme's functions.php file or you can create a separate file and include this at the bottom of functions.php file. <?php class similar_posts_widget extends WP_Widget {     function __construct()     {         parent::__construct('similar_posts_...

Java Program to calculate the Run Rate per over in a cricket match

import java.io.*; import java.util.*; public class RunRate{     Scanner scan=new Scanner(System.in);     int runs, balls;     float runRate;     public void input(){         try{             System.out.println("Enter Runs Scored: ");             runs=scan.nextInt();             System.out.println("Enter Balls Delivered: ");             balls=scan.nextInt();         }         catch(NumberFormatException e){             System.out.println("Error Code: "+e);             System.exit(0);   ...

Java Program to display Welcome Message

import java.io.*;// I/O package imported. public class Welcome{        //class name is "Welcome"     public Welcome(){      //constructor declaired to print the message.         System.out.println("Welcome to Java Programming Language!");/* System.out.println is used for output. Welcome Message is written within " ".*/     }//display() closes here.     public static void main(String[] args){        //main() is declaired to declair an object in it.         Welcome obj=new Welcome();  //Object "Obj" is bean created.     }//main() closes. }//class "Welcome" ends here. Above program displays the message which is written by you in " ".  In programs "/*" and "*/" are use for multiple line comment(s) and "//" is use for single line comment. Code line "Welc...