Step 1: HTML Markup:
<!-- -------------------- HTML -------------------- -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Toast Message In JavaScript</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
integrity="sha512-SnH5WK+bZxgPHs44uWIX+LLJAJ9/2PkPKZ5QiAj6Ta86w+fsb2TkcmfRyVX3pBnMFcV7oQPJkl9QevSCWr3W6A=="
crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<div class="btns">
<button onclick="toast('success')">Success</button>
<button onclick="toast('error')">Error</button>
</div>
<div class="toast-area"></div>
<script src="main.js"></script>
</body>
</html>
Step 2: Styling with CSS:
/*-------------------- CSS --------------------*/
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: sans-serif;
background: linear-gradient(#edf2ff, #ffe2d8);
min-height: 100vh;
}
.btns {
padding: 50px;
display: flex;
gap: 20px;
}
button {
background: #536;
border: 1px solid #536;
outline: none;
cursor: pointer;
font-weight: 600;
color: white;
padding: 10px 20px;
border-radius: 5px;
text-transform: capitalize;
}
.toast-area {
position: absolute;
padding: 20px;
right: 0;
bottom: 50px;
/* border: 1px solid red; */
display: flex;
flex-direction: column;
gap: 10px;
overflow: hidden;
}
.toast {
text-transform: capitalize;
background: #edf2ff;
padding: 20px;
width: 300px;
border-radius: 5px;
height: 70px;
font-weight: 600;
overflow: hidden;
position: relative;
display: flex;
align-items: center;
box-shadow: 0 0 10px #00000040;
transform: translateX(500px);
animation: anime 0.5s linear forwards;
}
@keyframes anime {
100% {
transform: translateX(0px);
}
}
.toast::after {
position: absolute;
content: '';
bottom: 0;
left: 0;
height: 5px;
width: 100%;
background: green;
animation: timebar 5s linear forwards;
}
.error::after {
background: red;
}
.toast i {
color: green;
font-size: 1.5rem;
margin-right: 20px;
}
.error i {
color: red;
}
@keyframes timebar {
100% {
width: 0%;
}
}
Step 3: Adding JavaScript Interaction:
//-------------------- Java Script --------------------//
function toast(msg) {
let toast = document.createElement('div');
toast.classList.add("toast");
let icon = '<i class="fa-solid fa-circle-check"></i>';
if (msg === 'error') {
toast.classList.add("error");
icon = '<i class="fa-solid fa-circle-xmark"></i>';
}
toast.innerHTML = `${icon} ${msg}`;
let toastArea = document.querySelector('.toast-area');
toastArea.appendChild(toast)
setTimeout(() => {
toast.remove();
}, 5000)
}
0 Comments