본문 바로가기

자바스크립트(jquery)

javascript 로딩 프로그래스바

반응형

xhr 을 이용하여 로딩 진행도 가져왔다.

upload ajax에 적용

//프로그래스라벨 html 추가 
let progressLabel = $('<td class="upload-progress"><progress max="100" value="0"></progress></td>');

//업로드함수 호출
uploadFile(file, progressLabel);

// 파일 업로드 함수
function uploadFile(file, progressLabel) {

	var formData = new FormData();
	formData.append('file', file);
	$.ajax({
		url: '/file_upload',
		type: 'POST',
		data: formData,
		processData: false,
		contentType: false,
		xhr: function() {
			var xhr = new XMLHttpRequest();
			xhr.upload.onprogress = function(event) {
				if (event.lengthComputable) {
					var percentComplete = (event.loaded / event.total) * 100;
					progressLabel.find('progress').attr('value', percentComplete);

                    //글 아래쪽에 있는 프로그래스바를 사용하고싶은 경우 
                    //setProgress 과 loading을 progressLabel 대신 사용하면 된다
				}
			};
			return xhr;
		},
		success: function(data) {
			console.log('File upload success.');
		},
		error: function(xhr) {
			console.log('File upload failed.');
		}
	});

}

 

로딩 중 화면에 띄워줄 mask와 progress_bar javascript

//프로그래스바
function setProgress(per) {
	if(per > 55){
		$(".progressPer").css("color", "#000");
	}
	per = per.toFixed(1);
	$(".progressPer").text(per+" %");
	$(".progressNow").css("width", "calc(" + per + "% - 20px)");
}

//반투명 마스크
function loading(){
	let maskHeight = $(document).height();
	let maskWidth = window.document.body.clientWidth;
	let mask = "<div id='mask' style='position:absolute; z-index:9997; background-color :#000000; display:none; left:0; top:0;'></div>";

	let loading = '';
	let loadingLocationX = maskWidth/2 - 100;   //화면 중앙에 로딩이미지 띄우기위한 x,y
	let loadingLocationY = maskHeight/2 - 100;  //이미지 크기에따라 -100 부분조절(테스트했던 이미지가 200*200 이라서 -100)
	loading += " <div id='loading'>";

	loading += " </div>";

	$('body').append(mask);
	$("#mask").css({
		'width' : maskWidth,
		'height' : maskHeight,
		'opacity' : '0.5'
	});

	let progressbar = '';
	progressbar += `
		<div class="progressContainer" id="progress_div" style='position:absolute; z-index:9998; text-align:center; display:block; margin-top:${loadingLocationY}px; margin-left:${loadingLocationX}px;'>
			<h3>검출중입니다</h3>
			<div class="progress progressTotal"></div>
			<div class="progress progressNow"></div>
			<div class="progress progressPer">0 %</div>
		</div>
	`;
	//mask에 세팅한 loading div를 append 후 show
	$('#mask').append(loading);
	$('#loading').append(progressbar)
	$("#mask").show();
}

//로딩 마스크 제거
function closeLoading(){
	$('#mask, #loading').hide();
	$('#mask, #loading').remove();
}

 

html 프로그래스바 스타일

<style>
	*{margin:0;padding:0}  //다른 스타일에 영향줄수 있으니 해당 margin라인은 제거하는 편이 좋음
	.progressContainer{position:relative;width: 450px;padding:20px 10px;margin-top: 15px;background:#000;height:40px;}
	.progress{position:absolute;width: calc(100% - 20px);height: 40px;}
	.progressTotal{background: #5D5D5D;border-radius: 20px;}
	.progressNow{width: calc(0% - 20px);background: #FFF;border-radius: 20px;}
	.progressPer{background: transparent; text-align:center;color:#A6A6A6; font-size: 25px; font-weight: bold;}
</style>

 

결과물

 

글자 위치를 조금 조정해야 할 듯 하다.

필요에 따라 글자위치 색감 등등 을 바꿔 사용하면 좋지 않을까...

만든지 2년이 된 코드인데 이것보다 좋은 코드가 많지만 그래도 직접 만든거니 어쩐지 정이간다