मॉडल पॉपअप (Modal Popup)
CSS और JavaScript से पॉपअप्स बनाने का कोड:
उदाहरण
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body { font-family: Arial, Helvetica, sans-serif; }
.popUp {
text-align: center;
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0; top: 0;
width: 100%; height: 100%;
background-color: rgba(0, 0, 0, 0.4);
}
.popupContent {
font-size: 20px;
font-weight: bold;
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
max-width: 500px; /* जोड़ा गया */
}
.close {
color: rgb(255, 65, 65);
float: right;
font-size: 40px;
font-weight: bold;
}
.close:hover, .close:focus {
color: #ff1010;
cursor: pointer;
}
</style>
</head>
<body>
<h1>पॉपअप उदाहरण</h1>
<button class="openPopUp">पॉपअप खोलें</button>
<h2>ऊपर के बटन पर क्लिक करके पॉपअप खोलें</h2>
<div class="popUp">
<div class="popupContent">
<span class="close">×</span>
<p>पॉपअप के अंदर सैंपल टेक्स्ट</p>
</div>
</div>
<script>
var popUp = document.querySelector(".popUp");
var btn = document.querySelector(".openPopUp");
var span = document.querySelector(".close");
btn.addEventListener("click", () => { popUp.style.display = "block"; });
span.addEventListener("click", () => { popUp.style.display = "none"; });
// बैकड्रॉप क्लिक पर बंद करें
window.onclick = function(event) {
if (event.target == popUp) { popUp.style.display = "none"; }
};
</script>
</body>
</html>
आउटपुट
- प्रारंभ में: "पॉपअप खोलें" बटन दिखता है
- बटन क्लिक करने पर: सेमी-ट्रांसपेरेंट बैकड्रॉप के साथ सेंटर में पॉपअप बॉक्स
- × या बैकड्रॉप क्लिक करने पर: पॉपअप बंद
मुख्य पैटर्न
position: fixed+ फुल स्क्रीन ओवरलेrgba(0,0,0,0.4)- डिम्ड बैकग्राउंडmargin: auto- वर्टिकल/हॉरिजॉन्टल सेंटरिंग- तीन तरीके से बंद: × बटन, बैकड्रॉप क्लिक, ESC की (जोड़ सकते हैं)
सुधार (आधुनिक)
// ESC की सपोर्ट
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && popUp.style.display === 'block') {
popUp.style.display = 'none';
}
});
// फोकस ट्रैपिंग
const focusable = popUp.querySelectorAll('button, a, input, select, textarea');
const first = focusable[0];
const last = focusable[focusable.length - 1];
popUp.addEventListener('keydown', (e) => {
if (e.key === 'Tab') {
if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
}
});
// खोलते समय फोकस
btn.addEventListener('click', () => {
popUp.style.display = 'block';
first.focus();
});
सीएसएस-ओनली मॉडल (नो JS)
.modal { display: none; }
#modal:target { display: block; }
/* HTML: Open ... */