Table of Contents

About

A modal is a overlay window behavior:

  • where its contents are the only elements that can receive focus.
  • When open, the user cannot interact with the rest of the page (nor can screen readers) until it's closed.
  • where the overlay is generally centered (or positioned from the top of the window) and therefore not located near the control / interactive element
  • where further user interactions is expected
  • an explicit close button is needed (though, it can be visually hidden).

It's a call to action where:

Not to be confound with an alert which is a dialog at the top or bottom of the page.

Event for show and hide

Next to an active click event, a modal (overlay, tooltip, …) on the web will be:

Example of snippets for your hide and show functions:

[
   ['mouseenter', showModal], // mouse hovers over the element
   ['mouseleave', hideModal], // mouse leaves the element area
   ['focus', showModal], // element becomes active
   ['blur', hideModal], // element becomes inactive
].forEach(([event, listener]) => {
   button.addEventListener(event, listener);
});

How to create a modal ?

Pure Css

Below you can find a minimum CSS implementation done without any library

  • for the box (centered on the viewport)
#modal {
    position: fixed; /* position top and left below calculated from the window */
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 4000 !important; /* On the top of all HTML element */
    padding: 1em; /* To get a bigger box */
    background: aliceblue; /* To see the box */    
}
  • for the dark background
#overlay {
  position: fixed;
  background-color: rgba(0,0,0,.6); /* Dark background */
  z-index: 10;
  top: 0;  
  right: 0;
  left: 0;
  bottom: 0;

}
body {
  overflow-y: hidden;
}
  • Page Example
<h2>Lorem ipsum</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam quis neque nibh. Fusce vitae sapien tincidunt, facilisis risus id, vulputate erat. Ut eget ex sem. Donec ornare consequat risus. Fusce cursus non lorem eu pharetra. Quisque in tristique orci. Nunc luctus turpis id augue euismod volutpat. Morbi ut nunc maximus, rhoncus ante at, feugiat nunc.
</p>
<p>
Fusce elementum urna augue, quis lobortis nunc lobortis ut. Nulla vitae arcu hendrerit, sodales lorem quis, ultrices neque. Suspendisse sed pretium diam, eget pretium sapien. Aenean accumsan sit amet ligula id condimentum. Cras sagittis scelerisque tellus, scelerisque ullamcorper dolor. Ut aliquet scelerisque quam. Morbi vel consequat tellus, non tempus erat.
</p>
<p>
Fusce elementum urna augue, quis lobortis nunc lobortis ut. Nulla vitae arcu hendrerit, sodales lorem quis, ultrices neque. Suspendisse sed pretium diam, eget pretium sapien. Aenean accumsan sit amet ligula id condimentum. Cras sagittis scelerisque tellus, scelerisque ullamcorper dolor. Ut aliquet scelerisque quam. Morbi vel consequat tellus, non tempus erat.
</p>
<div id="overlay">
  <div id="modal">The modal box</div>
</div>

HTML dialog

HTML - Dialog

<dialog id="ship">
 <form method=dialog>
  <p>A ship has arrived in the harbour.</p>
  <button type=submit value="board">Board the ship</button>
  <button type=submit value="call">Call to the captain</button>
 </form>
</dialog>
var ship = document.getElementById('ship');
ship.showModal();
ship.onclose = function (event) {
    if (ship.returnValue == 'board') {
       console.log("Board the ship");
   } else {
       console.log("Call the capitain");
   }
 };

Bootstrap

How to create a modal with Bootstrap?

jQuery UI Dialog

A dialog is a floating window that contains a title bar and a content area.

.mydialog {
 background: aliceblue;
}
$('#dialog').dialog(
	{
		autoOpen: true, // Open immeditaly
		width: '25%', // The width
		height: 'auto', // The height
		draggable: false, // Draggable from the header
		resizable: false, // Resizable from each side
		position: { my: "center", at: "center", of: window  }, // Position
		dialogClass: 'mydialog' // Additional class
	}
);
<h2>A page</h2>
<p>With a lot of text</p>
<div id="dialog" title="Dialog Title">
I'm a dialog with a 25% width in the middle of my window and a aliceblue background
</div>

React

You may use a positioning library such as FloatingUI dialog

Or do it your self. Example adapted from Modal with React

export default function Modal({ children }) {
  const overlay = useRef();
  const wrapper = useRef();

  const onDismiss = useCallback(() => {
    overlay.remove()
  }, [overlay]);

  const onClick = useCallback(
    (e) => {
      if (e.target === overlay.current || e.target === wrapper.current) {
        if (onDismiss) onDismiss();
      }
    },
    [onDismiss, overlay, wrapper]
  );

  const onKeyDown = useCallback(
    (e) => {
      if (e.key === "Escape") onDismiss();
    },
    [onDismiss]
  );

  useEffect(() => {
    document.addEventListener("keydown", onKeyDown);
    return () => document.removeEventListener("keydown", onKeyDown);
  }, [onKeyDown]);

  return (
    <div
      ref={overlay}
      className="fixed z-10 left-0 right-0 top-0 bottom-0 mx-auto bg-black/60"
      onClick={onClick}
    >
      <div
        ref={wrapper}
        className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-full sm:w-10/12 md:w-8/12 lg:w-1/2 p-6"
      >
        {children}
      </div>
    </div>
  );
}

jQueryModal

JQuery Plugin Modal is another Jquery plugin for modal

Library

Animation

Documentation / Reference