본문 바로가기
프로그래밍/Web

[WEB] 진행바(Progress Bar) 추가하기(블로그, 쇼핑몰)

by JR2 2021. 11. 6.

정확한 명칭은 Scroll Indicator 이다.

 

W3Schools online HTML editor

The W3Schools online code editor allows you to edit code and view the result in your browser

www.w3schools.com

 

W3Schools에서 scroll indicator를 검색해보면 예제가 나와있다.

그 중에서 내가 필요한 부분만 잘라냈다.

 

내가 제일 좋아하는 노래인 '당신과는 천천히'의 가사를 붙혀넣어 봤다.

See the Pen Untitled by Jirong (@jirongkim) on CodePen.


 

우선 가장 중요한 Javascript 부분을 해석해보자.

window.onscroll = function() {myFunction()};

window의 onscroll 이벤트는 현재 활성화 되어있는 창이 scroll 되었을 때 발생한다.

즉, 이 소스코드로 인해 스크롤이 발생되면 myFunction이라는 함수를 수행한다.

 

아래 소스코드가 myFunction이다.

function myFunction() {
  var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
  var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  var scrolled = (winScroll / height) * 100;
  document.getElementById("myBar").style.width = scrolled + "%";
}

1. winScroll로 top부터의 pixel 값을 받아온다. (body와 documentElement로 or 연산을 하는 이유는 모든 브라우저를 호환하기 위한 용도로 해석된다.)

2. 해당 페이지의 총 높이를 구한다(scrollHeight). 

3. 현재 활성화 되어서 보이는 높이를 구한다(clientHeight). (이건 브라우저의 높이를 줄이면 변동하는 정보임)

4. 2,3 번을 조합해 브라우저의 크기에 따라 높이를 계산한다. (이 과정이 없다면 브라우저의 높이가 엄청 작을 때 조금만 내려도 %가 엄청 올라갈 수 있다.)

5. 현재 scroll 값을(winScroll), 현재 브라우저의 높이 값(height)으로 나누고 100을 곱한다.

6. myBar의 width를 scrolled%로 조절한다.

 


.header {
  position: fixed;
  top: 0;
  z-index: 1;
  width: 100%;
  background-color: #f1f1f1;
}

background를 바꾸게 되면, Scroll Indicator가 적힌 부분의 색깔이 바뀌게 될 것이다.

top:0, position:fixed를 해줘야 상단에 고정이 될 것이다.

 

.progress-container {
  width: 100%;
  height: 8px;
  background: #ccc;
}

progressBar가 차는 배경이라고 생각하면 된다.

height는 progressBar의 두께이고, width는 100%로 해주어야한다.

 

.progress-bar {
  height: 8px;
  background: #04AA6D;
  width: 0%;
}

backgroud를 바꿈으로서 progressBar의 색깔을 바꿀 수 있다.

height는 progressBar의 두께이다.

width는 scroll이 움직이기 전 초기 상태이다. 0%로 두면 된다.

 

하나하나 바꿔보면서 어디가 바뀌는지 체크해보면 알기 쉬울 것이다.

 


 

<div class="header">
  <h2>Scroll Indicator</h2>
  <div class="progress-container">
    <div class="progress-bar" id="myBar"></div>
  </div>  
</div>

꼭 만들어준 class들을 넣어주어야 실제 웹페이지에 적용이 된다.

댓글