Name of code : alerte personnalisée
Categorie : JS Avancer
alerte personnalisée
<!DOCTYPE html>
<html>
<head>
<title>Alerte personnalisée</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
margin: 0;
padding: 0;
}
h1 {
text-align: center;
margin-top: 50px;
color: #007bff;
}
.alerteFond {
top: 0;
left: 0;
width: 100%;
height: 100%;
position: fixed;
background-color: #000000d6;
transition: opacity 0.2s ease-in-out;
}
.alerteFond.affichee {
opacity: 1;
}
.alerte {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
padding: 20px;
border-radius: 3px;
border: 2px solid #ccc;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
z-index: 9999;
opacity: 0;
transition: opacity 0.2s ease-in-out;
color: #333;
font-size: 18px;
line-height: 1.5;
text-align: center;
max-width: 80%;
overflow-wrap: break-word;
}
.alerte.affichee {
opacity: 1;
}
.alerte h2 {
margin-top: 0;
color: #007bff;
}
.alerte .croix {
position: absolute;
top: 5px;
right: 5px;
cursor: pointer;
color: #ff5c5c;
font-size: 24px;
transition: color 0.2s ease-in-out;
}
.alerte .croix:hover {
color: #ff3b3b;
}
.alerte .bouton {
display: block;
margin: 20px auto 0;
padding: 10px 20px;
background-color: #85837f;
color: #fff;
border: none;
cursor: pointer;
border-radius: 3px;
font-size: 16px;
transition: background-color 0.2s ease-in-out;
}
.alerte .bouton:hover {
background-color: #615c5c;
}
.alerte .text{
padding: 10px;
}
</style>
<script>
function afficherAlerte(message) {
var alerteFond = document.createElement('div');
var alerte = document.createElement('div');
alerteFond.classList.add('alerteFond');
alerte.classList.add('alerte');
var croix = document.createElement('span');
croix.classList.add('croix');
croix.innerHTML = '×';
croix.addEventListener('click', function() {
alerte.classList.remove('affichee');
alerteFond.classList.remove('affichee');
setTimeout(function() {
alerte.remove();
alerteFond.remove();
}, 200);
});
var contenu = document.createElement('div');
contenu.classList.add('text');
contenu.innerHTML = message;
var bouton = document.createElement('button');
bouton.classList.add('bouton');
bouton.innerHTML = 'OK';
bouton.addEventListener('click', function() {
alerte.classList.remove('affichee');
alerteFond.classList.remove('affichee');
setTimeout(function() {
alerte.remove();
alerteFond.remove();
}, 200);
});
alerte.appendChild(croix);
alerte.appendChild(contenu);
alerte.appendChild(bouton);
document.body.appendChild(alerteFond);
document.body.appendChild(alerte);
setTimeout(function() {
alerteFond.classList.add('affichee');
alerte.classList.add('affichee');
}, 10);
}
function afficherAlertePersonnalisee() {
afficherAlerte('Ceci est une alerte personnalisée !');
}
</script>
</head>
<body>
<h1>Exemple d'alerte personnalisée en JavaScript</h1>
<button onclick="afficherAlertePersonnalisee()">Afficher l'alerte</button>
</body>
</html>