Skip to content

Instantly share code, notes, and snippets.

@KaKi87
Last active March 25, 2018 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save KaKi87/9afde61374aec67e4479986683c4dc3e to your computer and use it in GitHub Desktop.
Save KaKi87/9afde61374aec67e4479986683c4dc3e to your computer and use it in GitHub Desktop.
One element progress bar
/*
One element progress bar
by KaKi87
22.03.18
*/
/*
Get browser prefix (for CSS)
https://stackoverflow.com/questions/8889014/setting-vendor-prefixed-css-using-javascript
https://davidwalsh.name/vendor-prefix
*/
var prefix = (function(){
var styles = window.getComputedStyle(document.documentElement, ''),
pre = (Array.prototype.slice
.call(styles)
.join('')
.match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o'])
)[1],
dom = ('WebKit|Moz|MS|O').match(new RegExp('(' + pre + ')', 'i'))[1];
return {
dom: dom,
lowercase: pre,
css: '-' + pre + '-',
js: pre[0].toUpperCase() + pre.substr(1)
};
})();
/**
* Progress object
* @param HTMLElement el progress element or parent
*/
function Progress(el){
// If element parameter is not of type progress, we create it as first child
if(!el.classList.contains('progress'))
{
el.appendChild(el = document.createElement('div'));
el.classList.add('progress');
}
this.el = el;
/**
* Set progress bar style
* @param {number} width progress bar width
* @param {number} height progress bar height
* @param {number} borderWidth progress bar border width
* @param {number} padding progress bar padding
* @param {color} color progress bar color
*/
this.style = function(width, height, borderWidth, padding, color){
this.width = width;
this.padding = padding;
Object.assign(this.el.style, {
width: `${width}px`,
height: `${height}px`,
border: `${borderWidth}px solid ${color}`,
background: `${prefix.css}linear-gradient(left, ${color},${color})`,
backgroundRepeat: 'no-repeat',
backgroundPosition: `${padding}px ${padding}px`,
backgroundSize: `0 ${height - padding * 2}px`
});
}
/**
* Set progress bar percentage
* @param number n percentage
*/
this.progress = function(n){
if(n > 100) return false;
this.percent = n;
this.el.style.backgroundSize = `${(this.width - this.padding * 2) * (n / 100)}px ${this.el.style.backgroundSize.split(' ')[1]}`;
}
}
/*
Progress bar init
*/
var p = new Progress(document.body);
p.style(300, 20, 2, 3, 'black');
/*
Progress animation example
*/
var i = 0;
setInterval(() => {
p.progress(i);
i++;
}, 20);
/*
Progress formula : (width - padding * 2) / progress
[Example]
Width : 300px
Padding : 3px
300 - 3 * 2 = 294
0% = 0 = 0 px
25% = 294 * 0.25 = 73.5 px
50% = 294 * 0.5 = 147 px
75% = 294 * 0.75 = 220.5 px
100% = 294 = 294 px
HTML code : <div class="progress"></div>
Compatible with inline-block.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment