โค้ดนี้เป็นการสร้างปุ่มที่สามารถแสดงสถานะการโหลด (loading state) โดยใช้ pseudo-element (::after) และ CSS animation
โค้ด CSS.loaderbutton {
padding: 10px 30px;
background: #3b71ca;
border: none;
color: #fff;
border-radius: 5px;
cursor: pointer;
font-size: 1.2em;
position: relative;
display: block;
}
.loaderbutton::after {
content: '';
display: block;
width: 1.1em;
height: 1.1em;
position: absolute;
left: calc(50% - 0.75em);
top: calc(50% - 0.75em);
border: 0.2em solid transparent;
border-right-color: white;
border-radius: 50%;
animation: loader-animation 0.7s linear infinite;
opacity: 0;
}
@keyframes loader-animation {
from {
transform: rotate(0);
}
to {
transform: rotate(360deg);
}
}
.loaderbutton.loading {
color: transparent;
}
.loaderbutton.loading::after {
opacity: 1;
}
โค้ด HTML
<button type="submit" class="loaderbutton" id="submit" >Submit</button>
<p id="result"></p>
โค้ด JavaScript
const loadBtn = document.getElementById("submit");
loadBtn.addEventListener('click', () => {
loadBtn.classList.add("loading");
const time = new Date();
document.getElementById("result").innerText = "to submit form and cannot double click\n";
document.getElementById("submit").disabled=true;
});
.loaderbutton
.loaderbutton::after
@keyframes loader-animation
.loaderbutton.loading