auto-progress-bar.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Auto Progress Bar Library with Scroll Activation
  2. document.addEventListener('DOMContentLoaded', () => {
  3. // Select all elements with the 'data-progress' attribute
  4. const progressBars = document.querySelectorAll('[data-progress]');
  5. // Intersection Observer configuration
  6. const observerOptions = {
  7. root: null, // viewport
  8. rootMargin: '0px',
  9. threshold: 0.3 // trigger when 30% of the element is visible
  10. };
  11. const animateProgressBar = (bar) => {
  12. const percentage = bar.getAttribute('data-percentage');
  13. const fill = bar.querySelector('.progress-bar__fill');
  14. // Animate fill
  15. setTimeout(() => {
  16. fill.style.width = `${percentage}%`;
  17. }, 100);
  18. };
  19. const observer = new IntersectionObserver((entries, observer) => {
  20. entries.forEach(entry => {
  21. if (entry.isIntersecting) {
  22. animateProgressBar(entry.target);
  23. observer.unobserve(entry.target); // Animate only once
  24. }
  25. });
  26. }, observerOptions);
  27. // Build the progress bars
  28. progressBars.forEach(bar => {
  29. const label = bar.getAttribute('data-label');
  30. const percentage = bar.getAttribute('data-percentage');
  31. const fillColor = bar.getAttribute('data-color');
  32. const trackColor = bar.getAttribute('data-bg');
  33. const textColor = bar.getAttribute('data-text-color');
  34. // Create header
  35. const header = document.createElement('div');
  36. header.classList.add('progress-bar__header');
  37. const labelSpan = document.createElement('span');
  38. labelSpan.classList.add('progress-bar__label');
  39. labelSpan.style.color = textColor;
  40. labelSpan.textContent = label;
  41. const percentageSpan = document.createElement('span');
  42. percentageSpan.classList.add('progress-bar__percentage');
  43. percentageSpan.style.color = textColor;
  44. percentageSpan.textContent = `${percentage}%`;
  45. header.appendChild(labelSpan);
  46. header.appendChild(percentageSpan);
  47. // Create track
  48. const track = document.createElement('div');
  49. track.classList.add('progress-bar__track');
  50. track.style.backgroundColor = trackColor;
  51. const fill = document.createElement('div');
  52. fill.classList.add('progress-bar__fill');
  53. fill.style.backgroundColor = fillColor;
  54. track.appendChild(fill);
  55. bar.appendChild(header);
  56. bar.appendChild(track);
  57. // Observe the progress bar for scroll
  58. observer.observe(bar);
  59. });
  60. });