Comment créer une fenêtre modale en html avec javascript ?
1 Answers
How to create a modal window in html with javascript?
Try this example:
html code
<!-- Modal window -->
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Modal content goes here...</p>
</div>
</div>
<!-- Button to open modal -->
<button id="myBtn">Open Modal</button>
css code
/* Modal styles */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgba(0,0,0,0.4); /* Black background with opacity */
}
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
js code
// Get the modal and the button that opens it
var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
Thank you.
1
Likes
0
Dislikes
Likes
Dislikes
0
Comments
Login to add comment