Progress bar JS
Hi!
This time I wanted to show you how to create simple loading bar using just JS and CSS.
HTML
For our HTML we will need button that will trigger our loading bar, loading text and also empty div as our progress bar. Lastly we need done loading text.
<button class="btn" onclick="showProgress()">Click</button>
<p id="loading">Loading ...</p>
<div id="progress-bar" class="progress-bar"> </div>
<p id="done">Done Loading!</p>
CSS
To create loading animation we will use keyframes.
.progress-bar{
/* display: none; */
margin-top: 10px;
margin-left: 50px;
border-radius: 25px;
background-color: #2962ff;
animation: loadBar 1s ease-in;
animation-fill-mode: forwards;
}
@keyframes loadBar {
0% {
width: 10px;
}
100% {
width: 200px;
}
}
Also we can add few styles to our texts and button.
#loading{
/* display: none; */
margin-top: 20px;
margin-left: 50px;
font-weight: 900;
}
#done{
/* display: none; */
margin-top: 20px;
margin-left: 50px;
font-weight: 900;
}
.btn{
margin-top: 50px;
margin-left: 50px;
padding: 10px 40px;
border: none;
border-radius: 25px;
background-color: #2962ff;
font-weight: 900;
color: aliceblue;
cursor: pointer;
}
Now our bar should look like this, on page load and also on refresh it should already load smoothly.
Next we will write few lines of JS to display it on click of a button. So first we can hide everything except our button. Just uncomment display:none attributes in our css.
JS
Here we will show our Loading text as well as our progress bar, that will automatically grow from left to right.
setTimeout() will be handy to end our animation and show Loading done text, at the same time hiding our Loading text and progress bar.
let progress_label = document.getElementById('loading')
let progress_bar = document.getElementById('progress-bar')
let progress_done = document.getElementById('done')
function showProgress(){
progress_label.style.display = 'block'
progress_bar.style.display = 'block'
setTimeout(() =>{
progress_label.style.display = 'none'
progress_bar.style.display = 'none'
progress_done.style.display = 'block'
},2000)
}
If you find any mistakes or you have ideas how to refactor my solutions to be simpler/ better please let me know :)
Subscribe to my newsletter
Read articles from Chris directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by