Notifications
Clear all
JavaScript Events
1
Posts
1
Users
0
Reactions
32
Views
Topic starter
18/09/2024 5:41 pm
Display a modal dialog when a button is clicked and hide it when the user clicks the close button or outside the modal.
Use Case: Modal for Additional Information
Show a modal that overlays the page when users click a button, and allow them to close it by clicking a close button or outside the modal.
Example:
<button id="openModal">Open Modal</button> <div id="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5);"> <div style="background: white; padding: 20px; margin: 100px auto; width: 300px; position: relative;"> <span id="closeModal" style="position: absolute; top: 10px; right: 10px; cursor: pointer;">X</span> <p>This is a modal window</p> </div> </div> <script> const modal = document.getElementById('modal'); const openModalButton = document.getElementById('openModal'); const closeModalButton = document.getElementById('closeModal'); openModalButton.addEventListener('click', function() { modal.style.display = 'block'; }); closeModalButton.addEventListener('click', function() { modal.style.display = 'none'; }); window.addEventListener('click', function(event) { if (event.target == modal) { modal.style.display = 'none'; } }); </script>