Skip to content

Instantly share code, notes, and snippets.

@yamoo9
Last active September 14, 2020 03:54
Show Gist options
  • Save yamoo9/3ecc947f767fe09115a87bb2c94b7bf3 to your computer and use it in GitHub Desktop.
Save yamoo9/3ecc947f767fe09115a87bb2c94b7bf3 to your computer and use it in GitHub Desktop.
GotoTop 컴포넌트
// 데모 모듈
(function Demo() {
'use strict';
// 컨트롤 할 문서 객체 참조
var goToTopBtn = null;
var goToTopBtnComponent = null;
window.addEventListener('DOMContentLoaded', function(){
goToTopBtn = document.querySelector('.go-to-top');
goToTopBtnComponent = new GotoTop(goToTopBtn, { duration: 0.3 });
autoSimulationCount = document.querySelector('.autoSimulationCount');
});
// 문서 객체를 전달하여 gotoTop 버튼 컴포넌트 객체 생성
// goToTop인스턴스 생성 과정에서 다음 옵션을 전달할 수 있습니다.
// var goToTopBtnComponent = new GotoTop(goToTopBtn, { duration: 0.3 });
// ---------------------------------------------------------------------
// 자동 시뮬레이션 횟수 변수
var simulationCount = 0;
var stopSimulationId = null;
var autoSimulationCount = null;
// 객체 지향 프로그래밍으로 제작된 컴포넌트는
// 아래 작성한 코드처럼 사용자 입장에서는 손쉽게 제어할 수 있습니다.
//
// goToTop인스턴스.show();
// goToTop인스턴스.hide();
// goToTop인스턴스.slideTo(스크롤 위치);
// goToTop인스턴스.slidePageTop();
function autoSimulation() {
// 자동 시뮬레이션 횟수 증가 → UI 업데이트
autoSimulationCount.textContent = ++simulationCount;
// 문서가 준비되면 goToTopBtnComponent 컴포넌트를 화면에서 보이도록 만듭니다.
goToTopBtnComponent.show();
// 1초가 지나면 goToTopBtnComponent 컴포넌트를 화면에서 감추도록 만듭니다.
window.setTimeout(function() {
goToTopBtnComponent.hide();
}, 1000);
// 2초가 지나면 창 스크롤 높이를 750으로 이동시킵니다.
window.setTimeout(function() {
goToTopBtnComponent.slideTo(750);
}, 2000);
// 4초가 지나면 goToTopBtnComponent 컴포넌트를 클릭 시뮬레이션 하여 페이지 상단으로 이동시킵니다.
window.setTimeout(function() {
goToTopBtnComponent.slidePageTop();
}, 4000);
// 자동 시뮬레이션 반복 (4.5초 뒤)
stopSimulationId = window.setTimeout(function() {
// 자동 시뮬레이션 함수 실행
autoSimulation();
}, 4500);
}
// 페이지 로딩과 동시에 자동 시뮬레이션 시키려면 아래 코드를 주석 해제합니다.
// autoSimulation();
// STOP 버튼을 누르면 자동 시뮬레이션 종료
function stopSimulation() {
window.clearTimeout(stopSimulationId);
}
// ---------------------------------------------------------------------
// START 시뮬레이션 함수 공개
window.autoSimulation = autoSimulation;
// STOP 시뮬레이션 함수 공개
window.stopSimulation = stopSimulation;
})();
// GotoTop 컴포넌트 모듈
(function GotoTopComponent() {
'use strict';
// @생성자_함수(ES6, class 역할)
function GotoTop(domNode, options) {
// 문서객체를 참조하여 컴포넌트 안에서 사용합니다.
this._button = domNode;
// jQuery 플러그인 옵션 객체를 떠올리세요.
options = options || {}; // options 매개변수가 없을 경우, 초기화
// 컴포넌트 환경구성을 설정합니다.
// mixins이란? 객체를 합성하는 패턴을 말합니다.
// jQuery 플러그인 사용 시, 사용자가 전달한 옵션 객체와 기본 옵션 객체가 합성되는 경우를 떠올리세요.
this._config = GotoTop.mixins(GotoTop.defaultOptions, options);
// 컴포넌트 초기화 메서드 실행
this._init();
}
// ——————————————————————————————————————————————————————————————————————
// @생성자_함수.속성 (ES6, class 멤버 역할)
// 컴포넌트 기본 옵션 객체입니다.
// 사용자가 전달한 options와 중복되는 속성은 options 속성으로 교체됩니다. (합성)
GotoTop.defaultOptions = {
scrollTarget: document.documentElement,
scrollDetectOfDocumentDivision: 4,
scrollPosition: 0,
duration: 0.4
}
// @생성자_함수.메서드 (ES6, class 멤버 역할)
// 함수는 객체이므로 객체.속성 = 함수(값) 설정이 가능합니다.
// 쉽게 말해 유틸리티 함수입니다.
GotoTop.mixins = function() {
// 함수가 전달 받은 전달인자(유사 배열) 객체를 배열로 변경합니다.
var args = [].slice.call(arguments);
// 배열 객체의 reduce() 메서드를 사용해 배열 아이템을 순환한 후,
// 합성(mixin) 객체를 반환합니다. 이 함수의 역할은 jQuery 플러그인 사용 시
// 사용자 전달 옵션을 플러그인 기본 옵션과 합성하는 것과 유사합니다.
//
// reduce() 메서드는 IE 9+ 지원합니다.(참고: https://mzl.la/38IBYlc)
var mixinObject = args.reduce(function(accumulator, currentObject) {
// for-in 문을 사용해 currentObject 객체를 순환합니다.
for (var key in currentObject) {
// currentObject 객체 자신의 속성만 처리합니다.
// 이유는 프로토타입 체인으로 인해 불필요한 순환을 막기 위해서 입니다. (성능 저하 차단)
if (currentObject.hasOwnProperty(key)) {
// 합성 객체인 accumulator의 속성을 currentObject의 속성으로 덮어씁니다.
accumulator[key] = currentObject[key];
}
}
// 순환이 마무리 되면 합성 객체를 반환합니다.
return accumulator;
}, {}); // 2번째 인자는 초기 값을 설정하는 것입니다.
return mixinObject;
}
// ——————————————————————————————————————————————————————————————————————
// @프로토타입_객체
// 생성자 함수를 통해 생성된 인스턴스 객체가 사용 가능한 멤버입니다.
// 초기화 인스턴스 메서드 (비공개: 이름 관례 규칙에 따라 _비공개 설정)
GotoTop.prototype._init = function() {
// 참조된 문서 객체에 클릭 이벤트를 연결합니다.
// 이벤트 핸들러(함수)로 컴포넌트 인스턴스 메서드를 연결합니다.
// .bind()를 사용해 this 컨텍스트를 컴포넌트 인스턴스 객체로 설정합니다.
this._button.addEventListener('click', this.slidePageTop.bind(this));
// window 객체의 스크롤 이벤트를 감지하는 이벤트를 연결합니다.
window.addEventListener('scroll', this._scrollDetection.bind(this));
}
// window 스크롤 감지 메서드 (비공개)
GotoTop.prototype._scrollDetection = function(e) {
// 컴포넌트 옵션 객채 설정 값을 각 변수에 참조 또는 복사합니다.
var division = this._config.scrollDetectOfDocumentDivision;
// getBoundingClientRect() 메서드는 IE 4+ (참고: https://mzl.la/3bPOEJ5)
var documentHeight = document.body.getBoundingClientRect().height;
// window 스크롤 높이
var scrollPos = window.scrollY || window.pageYOffset;
// 스크롤 높이를 감지하여 스크롤 버튼을 UI에 보임/감춤 처리 합니다.
if ( scrollPos > (documentHeight / division) ) {
this.show();
} else {
this.hide();
}
}
// 페이지 상단으로 슬라이드 이동 메서드 (공개)
// new GotoTop(문서객체, 옵션).slidePageTop() 으로 실행 가능하도록 공개 설정합니다.
GotoTop.prototype.slidePageTop = function() {
// 컴포넌트 옵션 객채 설정 값을 각 변수에 참조 또는 복사합니다.
var position = this._config.scrollPosition;
this.slideTo(position);
}
// 슬라이드 이동 메서드(공개)
GotoTop.prototype.slideTo = function(pos) {
var target = this._config.scrollTarget;
var duration = this._config.duration;
// gsap(v3) 문법으로 변경합니다.
gsap.to(target, { duration: duration, scrollTop: pos });
}
// 버튼 보임 메서드 (공개)
GotoTop.prototype.show = function() {
// gotoTop 버튼
var button = this._button;
// 컴포넌트 옵션 객채 설정 값을 각 변수에 참조 또는 복사합니다.
var duration = this._config.duration;
gsap.to(button, { duration: duration, autoAlpha: 1 });
}
// 버튼 감춤 메서드 (공개)
GotoTop.prototype.hide = function() {
var button = this._button;
var duration = this._config.duration;
gsap.to(button, { duration: duration, autoAlpha: 0 });
}
// ——————————————————————————————————————————————————————————————————————
// 컴포넌트 공개
window.GotoTop = GotoTop;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment