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

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);   ...

Vanilla Javascript each()

JQuery's each() is very useful when iterating through elements. But you don't want to use JQuery in your project you can simply add the following javascript code which works somewhat similar to the JQuery's each function. Here the fnc parameter is the function string which is converted to a valid function call replacing all the $(this) with this /**  * This function binds a particular function to every element with the specified selector. It is somewhat same as JQuery's each() with less functionality  * @param {String|DOMElement} selector  * @param {Function} fnc  */ function each(selector, fnc) {     var elem;     if (typeof selector === "string") {         elem = $_(selector);     } else {         elem = selector;     }     fnc = (fnc.toString().replace("$(this)", "elem") + "();").replace("function () {", "").replac...

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...