Creating a modal using JavaScript involves manipulating the CSS and DOM to show or hide a modal overlay and its content. Here's an example of how you can create a modal:
<!DOCTYPE html>
<html>
<head>
<title>Modal Example</title>
<link rel="stylesheet" href="styles.css">
<style>#modalOverlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 9999;
}
#modalContent {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
padding: 20px;
text-align: center;
}
#modalContent h2 {
margin-top: 0;
}
#closeModal {
margin-top: 20px;
}
</style>
</head>
<body>
<button id="openModal">Open Modal</button>
<div id="modalOverlay">
<div id="modalContent">
<h2>Modal Title</h2>
<p>This is the modal content.</p>
<button id="closeModal">Close Modal</button>
</div>
</div>
<script src="script.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
const openModalButton = document.getElementById('openModal');
const closeModalButton = document.getElementById('closeModal');
const modalOverlay = document.getElementById('modalOverlay');
function openModal() {
modalOverlay.style.display = 'block';
}
function closeModal() {
modalOverlay.style.display = 'none';
}
openModalButton.addEventListener('click', openModal);
closeModalButton.addEventListener('click', closeModal);
});
</script>
</body>
</html>
Place all the files (HTML, CSS, and JS) in the same folder.
Open the HTML file in a web browser, and you should see a button labeled "Open Modal." When you click the button, a modal overlay with the title, content, and a "Close Modal" button will appear. Clicking the "Close Modal" button will hide the modal overlay.
Note: Adjust the CSS classes and styles as per your design requirements. You can customize the modal further by adding animations, resizing options, or additional functionality such as form inputs or dynamic content.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc