728x90
안녕하세요 오늘은 자바스크립트와 html 을 이용해 Progress Bar를 만들어보도록 하겠습니다.
프로그레스바는 사용자가 진행 상황을 시각적으로 쉽게 파악할 수 있도록 도와주는 UI 요소로, 다음과 같은 경우에 자주 사용됩니다:
- 파일 업로드/다운로드: 대용량 파일 전송 시, 작업 진행 상황을 보여줍니다.
- 로딩 화면: 데이터나 리소스 로드 시 사용자가 대기 상태를 이해할 수 있도록 제공합니다.
- 폼 진행: 멀티 스텝 폼이나 설문지의 현재 진행 상황을 표시합니다.
- 게임 및 학습 앱: 게임 레벨 진행이나 학습 목표 달성도를 표현하는 데 유용합니다.
progressBar.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Progress Bars</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.progress-container {
margin-bottom: 20px;
}
.progress-bar {
width: 100%;
background-color: #f3f3f3;
border-radius: 5px;
overflow: hidden;
height: 20px;
margin: 10px 0;
}
.progress-bar div {
height: 100%;
width: 0;
background-color: #4caf50;
transition: width 0.2s;
}
.label {
margin-bottom: 5px;
}
.time-input {
margin-top: 5px;
}
.start-button {
margin: 20px 0;
padding: 10px 20px;
font-size: 16px;
background-color: #4caf50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Progress Bars</h1>
<div id="progress-bars"></div>
<button class="start-button" id="start-button">Start</button>
<div class="progress-container">
<div class="label">Overall Progress:</div>
<div class="progress-bar" id="overall-bar">
<div></div>
</div>
</div>
<script>
const numItems = 5;
const progressBars = document.getElementById("progress-bars");
const overallBar = document.getElementById("overall-bar").children[0];
const startButton = document.getElementById("start-button");
let totalDuration = 0;
let completedItems = 0;
function createProgressBar(index) {
const container = document.createElement("div");
container.className = "progress-container";
const label = document.createElement("div");
label.className = "label";
label.innerText = `Item ${index + 1}`;
const progressBar = document.createElement("div");
progressBar.className = "progress-bar";
const progress = document.createElement("div");
progressBar.appendChild(progress);
const input = document.createElement("input");
input.type = "number";
input.className = "time-input";
input.placeholder = "Enter time (seconds)";
input.min = 1;
container.appendChild(label);
container.appendChild(progressBar);
container.appendChild(input);
progressBars.appendChild(container);
return { progress, input };
}
function updateOverallProgress() {
const overallPercentage = (completedItems / numItems) * 100;
overallBar.style.width = overallPercentage + "%";
}
function startProgress() {
const items = document.querySelectorAll(".progress-container");
completedItems = 0;
totalDuration = 0;
items.forEach((item, index) => {
const input = item.querySelector(".time-input");
const progress = item.querySelector(".progress-bar div");
const seconds = Math.max(parseInt(input.value, 10) || 0, 1);
totalDuration += seconds;
progress.style.width = "0%";
let startTime = Date.now();
const interval = setInterval(() => {
const elapsedTime = Date.now() - startTime;
const percentage = Math.min((elapsedTime / (seconds * 1000)) * 100, 100);
progress.style.width = percentage + "%";
if (percentage >= 100) {
clearInterval(interval);
completedItems++;
updateOverallProgress();
}
}, 100);
});
}
startButton.addEventListener("click", startProgress);
for (let i = 0; i < numItems; i++) {
createProgressBar(i);
}
</script>
</body>
</html>
위 코드는 사용자로부터 5개의 개별 프로그레스바의 소요 시간을 입력 받아서 전체 진행 상황을 함께 보여주는
프로그레스바를 구현합니다.
사용자가 5개의 프로그레스의 시간을 입력한 후 start 를 누르면 동시에 progress bar 가 실행됩니다.
진행 상황은 일정 간격을 두고 갱신되며 완료되면 전체 진행률이 자동으로 계산되어 나타납니다.
위 예제를 바탕으로 취소버튼, 진행 중 다른 애니메이션을 추가하는 등 더 복잡한 기능을 추가할 수도 있습니다.
감사합니다
'JavaScript' 카테고리의 다른 글
[JavaScript] Jest로 유닛 테스트 작성하기 (1) | 2025.01.19 |
---|---|
[JavaScript] 지연 평가(Lazy Evaluation) (0) | 2025.01.16 |
[JavaScript] 모나드(Monad) (0) | 2025.01.09 |
[JavaScript] 순수 함수(Pure Function) (0) | 2025.01.03 |
[JavaScript] 커링(Currying) (2) | 2024.12.28 |