Basic modals

HTML popup windows do not exist

There is no such thing as a poup windows in the HTML world.

You have to create the illusion of it stylizing a fragment of the main HTML page, and hiding and showing it as required.

Isn’t this cheating ?

A basic modal box with pure Javascript supplies an example; here is the code:

Isn’t this too much fuss for such a simple task ?

w3school modal example

w3school modal example

Well, actually it’s not that bad.

Here is how it works:

  • a semi-transparent and initially hidden “modal” element covers the whole html page, thus providing a backdrop
  • a nested “modal content” element has been given the style to look as a popup window
  • you can show or hide the modal by playing with it’s display CSS attribute
<script language="javascript">

    $(document).ready(function() {

        // Get the modal
        var modal = $('#my-modal');

        // Open the modal
        var button = $('#button-open-modal');
        button.on('click', function(event) {
            modal.css('display', 'block');

        // Close the modal
        var close_button = $('.close');
        close_button.on('click', function(event) {
            modal.css('display', 'none');

        // When the user clicks anywhere outside of the modal, close it
        $(window).on('click', function(event) {
            if ( == modal.attr('id')) {
                modal.css('display', 'none');




Check sample code at: (1) A basic modal box with jQuery

A modal which returns a value

How can we collect a value from the user in the modal window, and return it to the main page ?

We have access to any javascript functions available (after all, we’re living in the same HTML page), so we can call any helper just before closing the modal.

function close_popup(modal) {
    var value = modal.find('.my-modal-body input').val();

function save_text_value(value) {
    if (value) {
    else {


Check sample code at: (2) A basic modal box which returns a value


Always remember to clean the input box every time before showing the modal box, as this will be reused again and again …

function open_popup(modal) {
    var input = modal.find('.my-modal-body input');

Bootstrap 3 modal plugin

Bootstrap 3 provides a specific plugin to handle modals:

You can ask for a larger or smaller dialog specifing either ‘modal-lg’ or ‘modal-sm’ class.

The pluging fires some specific events during the modal life cycle:


Check sample code at: (3) A basic modal box with Bootstrap 3