Create Pop up Form in JavaScript

 


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pop-Up Form</title>
<style>
/* Basic styles for the page */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
box-sizing: border-box;
}

/* Overlay background */
.modal-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
z-index: 1000;
}

/* Modal box */
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
z-index: 1001;
width: 300px;
display: none;
}

/* Close button */
.modal-close {
float: right;
cursor: pointer;
color: red;
font-size: 18px;
}

/* Form styling */
form {
display: flex;
flex-direction: column;
}

form label {
margin-top: 10px;
}

form input, form button {
padding: 8px;
margin-top: 5px;
}

form button {
background: blue;
color: white;
border: none;
cursor: pointer;
}

form button:hover {
background: darkblue;
}
</style>
</head>
<body>
<h1>Welcome to My Page</h1>
<button id="openModal">Open Form</button>

<!-- Modal Structure -->
<div class="modal-overlay" id="modalOverlay"></div>
<div class="modal" id="modal">
<span class="modal-close" id="closeModal">&times;</span>
<h2>Contact Form</h2>
<form id="popupForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>
</div>

<script>
// Get references to elements
const openModalButton = document.getElementById('openModal');
const closeModalButton = document.getElementById('closeModal');
const modal = document.getElementById('modal');
const modalOverlay = document.getElementById('modalOverlay');

// Function to open the modal
const openModal = () => {
modal.style.display = 'block';
modalOverlay.style.display = 'block';
};

// Function to close the modal
const closeModal = () => {
modal.style.display = 'none';
modalOverlay.style.display = 'none';
};

// Event listeners
openModalButton.addEventListener('click', openModal);
closeModalButton.addEventListener('click', closeModal);
modalOverlay.addEventListener('click', closeModal);

// Submit form handler
const popupForm = document.getElementById('popupForm');
popupForm.addEventListener('submit', (e) => {
e.preventDefault();
alert('Form submitted!');
closeModal();
});
</script>
</body>
</html>

Comments

Popular posts from this blog

ការសរសេរ JavaScript ចូលក្នុង Web Page

ការប្រើ Switch ក្នុង JavaScript