🧑‍💻개발/jQuery

[jQuery]페이지의 스크롤에 따라 진행바 만들기

무택 2023. 5. 29.

 

 

안녕하세요 무택입니다 :)

오늘은 스크롤에 따라 진행상태를 알려주는 바 만드는 코드에 대해 남겨보려고 합니다. 요즘 아티클 형식의 페이지는 거의 다 사용하고 있는 것 같은데 그만큼 웹사이트 사용성에 도움을 주는 기능이라고 생각합니다. 사람들이 페이지에 들어와서 글을 읽다가 어느 정도 남았는지 직관적으로 알 수 있기 때문에 적절한 페이지에 적용하면 좋은 기능이 될 것 같아요.

 

 

 

동작원리

저는 기능을 브런치 사이트의 아티클 페이지를 참조해서 만들었습니다. 그래서 기본적으로 동작 원리는 스크롤할 때마다 스크립트를 실행시켜서 현재 스크롤 위치를 파악 후 수치로 변환(0 ~ 100%), 그 수치를 진행바의 넓이로 넣는 원리입니다.

 

 

 

codepen 예시

See the Pen 스크롤 위치 by TytanLee (@TytanLee) on CodePen.

 

 

HTML

<script src="https://code.jquery.com/jquery-3.6.4.min.js"
        integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script>
<nav id="top">
  <div class="progressBarWrap">
    <span class="progressBar"></span>
  </div>
</nav>
<div class="back">
  <div id="thum"></div>
</div>

 

CSS

* {
  padding: 0;
  margin: 0;
}

.back {
  width: 100%;
  height: 500vh;
  background-color: #999;
}

#top {
  position: relative;
  width: 100%;
  height: 20vh;
  background-color: #fff;
  z-index: 999;
  transition: all .2s ease-in-out 0s;
  opacity: 1;
}

.progressBarWrap {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #e4ffe6;
}

.progressBar {
  position: absolute;
  bottom: 0px;
  left: 0px;
  width: 0%;
  height: 2px;
  background: #00ff12;
  z-index: 9999999;
  transition: all .3s ease-out;
}

#thum {
  position: relative;
  background-color: #c8c8c8;
  height: 200px;
}

 

JS(jQuery)

//스크롤 진행 퍼센트 나타내기
$(window).scroll(function () {
  var scrollY = ($(window).scrollTop() / ($(document).height() - $(window).height()) * 100).toFixed(3);
  $(".progressBar").css({
    "width": scrollY + "%"
  });
});

//게시글 들어왔을때 nav+스크롤 진행 활성화
$(window).scroll(function () {
  let top = document.getElementById("top");
  let navHeight = $("#top").height();
  let thumHeight = $("#thum").height();
  let scrollY = $(window).scrollTop();

  if (scrollY > navHeight) {
    top.style.opacity = '0';
  } else {
    top.style.opacity = '1';
  }
  //스크롤 위치가 네비 높이랑 썸네일 높이 더한것보다 커지면 네비 나타나고 스크롤 진행바 나타내기
  if (scrollY > navHeight + thumHeight) {
    top.style.opacity = '1';
    top.style.position = 'fixed';
    top.style.backgroundColor = 'rgba(255, 255, 255, .95)';
  }
});

 

 

 JS코드 설명

$(window).scroll(function () {
  var scrollY = ($(window).scrollTop() / ($(document).height() - $(window).height()) * 100).toFixed(3);
  $(".progressBar").css({
    "width": scrollY + "%"
  });
});

 

먼저 $(window).scroll(function()으로 스크롤할 때마다 기능이 실행되게 설정을 먼저 한 뒤, scrollY에 스크롤 위치를 저장합니다. 스크롤 위치를 저장하는 원리는

$(window).scrollTop() / ($(document).height() - $(window).height()

 

이 계산식을 사용하면 스크롤의 위치가 0.1784511251...이런식으로 소수점자리로 나옵니다. 여기서 나온 숫자에서 소수점 앞자리 두 개가 %가 됩니다. (ex. 0.1523845..이라면 15%가 현재 스크롤 위치)

그렇기 때문에 100을 곱해서 소수점 두 자리는 살려주고 .toFixed(3)으로 나머지 소수점 세 자리까지만 계산하도록 세팅해 줍니다.(소수점을 많이 넣을수록 스크롤 위치를 세세하게 잡을 수 있어요)

 

그리고 진행퍼센트를 나타내줄 Progress Bar 값을 가져와서 이 영역의 width를 위에서 구한 스크롤 위치 값으로 넣어주면 끝!

 

 

//게시글 들어왔을때 nav+스크롤 진행 활성화
$(window).scroll(function () {
  let top = document.getElementById("top");
  let navHeight = $("#top").height();
  let thumHeight = $("#thum").height();
  let scrollY = $(window).scrollTop();

  if (scrollY > navHeight) {
    top.style.opacity = '0';
  } else {
    top.style.opacity = '1';
  }
  //스크롤 위치가 네비 높이랑 썸네일 높이 더한것보다 커지면 네비 나타나고 스크롤 진행바 나타내기
  if (scrollY > navHeight + thumHeight) {
    top.style.opacity = '1';
    top.style.position = 'fixed';
    top.style.backgroundColor = 'rgba(255, 255, 255, .95)';
  }
});

 

그리고 그 아래 코드들은 썸네일 부분의 높이값으로 위치를 가져와서 스크롤 위치가 썸네일을 지나가면 nav가 다시 나오도록 만든 코드입니다.

간단하게 설명하면 상단 nav의 높이, 썸네일 부분의 높이를 변수로 가져옵니다. 기본적으로 스크롤 위치 값이 상단 nav 높이 값보다 커지면 투명도를 0으로 만들어야 다음에 등장할 때 투명도가 0에서 1로 되기 때문에 먼저 그 설정을 해주고 스크롤의 위치가 상단 nav의 높이+ 썸네일 부분의 높이보다 커지면 스크롤진행바의 투명도를 1로 줘서 보이게 만들어줍니다.