Simple modals using CSS and Javascript with no other dependencies.
- Import
modal.cssinto your HTML file - Import
modal.jsat the bottom of your HTML file. - Add the following code to your HTML, wherever you want a modal trigger:
<!-- Trigger for the Modal -->
<button class="modal-triggers" data-target="myModal">Click me</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="modal-close">×</span>
I am a modal!
</div>
</div>
That's it!
To use this example:
- Copy this into a file and title it
mymodal.html. - Add files
modal.cssandmodal.jsinto the same directory asmymodal.html
<html>
<head>
<link type="text/css" rel="stylesheet" href="modal.css" />
<title>Page with modals</title>
</head>
<body>
<!-- Trigger for the Modal -->
<button class="modal-triggers" data-target="myModal">Click me</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="modal-close">×</span>
I am a modal!
</div>
</div>
<script src="modal.js"></script>
</body>
</html>
You can also open a modal manually with javascript, via the open_modal function. This could be useful if you only want to open a modal after doing some task, such as making a server call and waiting for its response.
In that case, you need only call the funtion open_modal(document.getElementById("my-manual-modal")); where my-manual-modal is a div of class modal such as the one in example above.
In this dummy example, I am just opening the modal when the page loads. Obviously, you'd want to do something more useful. For example, you might make an API call to the server; when the server returns data, you could modify the text in the <p> element inside the modal-content div, and then open the modal.
<html>
<head>
<link type="text/css" rel="stylesheet" href="modal.css" />
<title>Page with modals</title>
</head>
<body>
<!-- The Modal -->
<div id="manual-modal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="modal-close">×</span>
<p>Modal opened by javascript.</p>
</div>
</div>
<script src="modal.js"></script>
<script>
open_modal(document.getElementById("manual-modal"))
</script>
</body>
</html>
If employing this in a mobile environment, ensure you have a meta viewport tag, with minimum-scale=1, such as:
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
If you do NOT have this, then you might run into an issue on chromium based browsers: If there is an element on the page with height exceeding veiwport height, then Chrome might adjust the viewport height. As a result, if you click a modal trigger while that element is in view, the modal might drift out of the viewport. In my experience, adding minimum-scale=1 to the meta viewport tag solves this issue.