Fork me on GitHub

A basic modal box with pure Javascript

view code

w3schools.com supplies an example; here is the full code:

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal2

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 (event.target.id == modal.attr('id')) {
                modal.css('display', 'none');
            }
        });

    });

</script>

Code sample

A basic modal box with pure Javascript ...
×

Modal Header

Some text in the Modal Body

Some other text...