Visibility
Visibility (Visibility 가시성 동작)
Visibility는 특정 가시성 이벤트가 발생할 때 트리거되는 콜백 집합을 어떤 요소에든 연결할 수 있게 해주는 동작 모듈이에요. 지연 로딩, 무한 스크롤, 스크롤 기반 반응형 콘텐츠, 고정 헤더 등을 구현할 때 유용해요.
출처: 문서
본문
Introduction (소개)
Visibility는 어떤 요소에든 연결할 수 있고 특정 가시성 이벤트가 발생하면 트리거되는 콜백 집합을 제공해요.
가시성에 이벤트를 연결하는 데는 여러 가지 용도가 있어요. 자주 쓰이는 것들 중 일부는 다음과 같아요.
- Lazy Loading Images (이미지 지연 로딩): 사용자가 이미지를 보기 직전에 이미지 로딩을 시작하고 싶을 때
- Reactive Content (반응형 콘텐츠): 요소가 사용자가 스크롤한 정도에 따라 바뀌도록 하고 싶을 때
- Sticky Headers (고정 헤더): 요소가 지나가면 뷰포트에 고정시키고, 이후에는 원래 정적 위치로 돌아가게 하고 싶을 때
- Event Tracking (이벤트 추적): 사용자의 콘텐츠 참여도에 매칭되는 분석 이벤트를 연결하고 싶을 때. 예: 블로그 글이 30% 읽혔을 때 Google Analytics에 기록
- Infinite Scroll (무한 스크롤): 사용자가 콘텐츠를 일부 스크롤했을 때 컨테이너에 더 많은 콘텐츠를 로딩하고 싶을 때
Usage (사용법)
How To Use (사용 방법)
Visibility는 요소의 화면 내 위치에 이벤트를 연결하는 데 사용할 수 있는 콜백 집합을 제공해요.
// some example callbacks
$('.demo.segment')
.visibility({
onTopVisible: function(calculations) {
// top is on screen
},
onTopPassed: function(calculations) {
// top of element passed
},
onUpdate: function(calculations) {
// do something whenever calculations adjust
updateTable(calculations);
}
})
;
각 콜백은 계산된 값을 첫 번째 매개변수로 받아요. onTopVisible은 요소 상단이 화면에 있을 때, onTopPassed는 요소 상단이 지나갔을 때, onUpdate는 계산이 조정될 때마다 실행돼요. 계산 결과에는 다음 값들이 포함돼요.
Calculation
Value
pixelsPassed (지나간 픽셀)
percentagePassed (지나간 비율)
fits (맞는지)
width (너비)
height (높이)
onScreen (화면에 있는지)
offScreen (화면 밖인지)
passing (지나가는 중인지)
topVisible (상단이 보이는지)
bottomVisible (하단이 보이는지)
topPassed (상단이 지나갔는지)
bottomPassed (하단이 지나갔는지)
Changing Callback Frequency (콜백 빈도 변경)
Visibility의 기본 설정에서는 조건이 충족되는 첫 번에만 각 콜백이 발생해요. 이후에 다시 조건이 충족돼도 이벤트는 발생하지 않아요.
Clear (지우기)
Once (한 번)
Continuous (지속)
Event Log (이벤트 로그)
Callbacks (콜백)
콜백은 두 가지 범주로 나뉘어요. 표준 이벤트는 조건이 true로 평가되는 첫 번째 애니메이션 프레임에서 발생해요.
Standard Events (표준 이벤트)
Event (이벤트)
Occurs (발생 조건)
Pseudocode (의사 코드)
onOnScreen
Any part of element is in current scroll viewport (요소의 일부가 현재 스크롤 뷰포트에 있음)
screen.bottom >= element.top && screen.bottom
onOffScreen
No part of element is in current scroll viewport (요소의 어떤 부분도 현재 스크롤 뷰포트에 없음)
screen.bottom = element.bottom
onTopVisible
Element's top edge has passed bottom of screen (요소의 상단 가장자리가 화면 하단을 지나감)
screen.bottom >= element.top
onTopPassed
Element's top edge has passed top of the screen (요소의 상단 가장자리가 화면 상단을 지나감)
screen.top >= element.top
onBottomVisible
Element's bottom edge has passed bottom of screen (요소의 하단 가장자리가 화면 하단을 지나감)
screen.bottom >= element.top
onPassing
Any part of an element is visible on screen (요소의 일부가 화면에 보임)
screen.bottom >= element.top && screen.top
onBottomPassed
Element's bottom edge has passed top of screen (요소의 하단 가장자리가 화면 상단을 지나감)
screen.top >= element.bottom
Grouped Events (그룹 이벤트)
onPassed는 요소의 특정 비율이나 픽셀을 지나갔을 때 발생하는 콜백의 모음을 지정할 수 있게 해줘요.
Event (이벤트)
Occurs (발생 조건)
Example (예제)
onPassed {}
A distance from the top of an element's content has been passed, either as a percentage or in pixels (요소 콘텐츠 상단으로부터의 거리가 지나갔음, 비율이나 픽셀로)
onPassed: {
40: function() {
// do something when having passed 40 pixels.
},
'80%': function() {
// do something at 80%
}
}
Reverse Events (역방향 이벤트)
역방향 이벤트는 사용자가 페이지를 다시 위로 스크롤할 때 동일한 조건에서 발생해요.
Event (이벤트)
Occurs (발생 조건)
Pseudocode (의사 코드)
onTopVisibleReverse
Element's top edge has not passed bottom of screen (요소의 상단 가장자리가 화면 하단을 지나지 않음)
screen.bottom >= element.top
onTopPassedReverse
Element's top edge has not passed top of the screen (요소의 상단 가장자리가 화면 상단을 지나지 않음)
screen.top >= element.top
onBottomVisibleReverse
Element's bottom edge has not passed bottom of screen (요소의 하단 가장자리가 화면 하단을 지나지 않음)
screen.bottom >= element.top
onPassingReverse
Element's top has not passed top of screen but bottom has (요소 상단은 화면 상단을 지나지 않았지만 하단은 지나감)
screen.bottom >= element.top && screen.top
onBottomPassedReverse
Element's bottom edge has not passed top of screen (요소의 하단 가장자리가 화면 상단을 지나지 않음)
screen.top >= element.bottom
Behaviors (동작)
Visibility는 컴포넌트와 상호작용하기 위한 여러 유용한 동작을 포함해요.
Behavior (동작)
Usage (용도)
disable callbacks
Disable callbacks temporarily. This is useful if you need to adjust scroll position and do not want to trigger callbacks during the position change. (콜백을 일시적으로 비활성화. 스크롤 위치를 조정하는 동안 콜백을 트리거하고 싶지 않을 때 유용)
enable callbacks
Re-enable callbacks (콜백 다시 활성화)
is on screen
Returns whether element is on screen (요소가 화면에 있는지 반환)
is off screen
Returns whether element is off screen (요소가 화면 밖인지 반환)
get pixels passed
Returns number of pixels passed in current element from top of element (요소 상단에서 현재 요소에 지나간 픽셀 수 반환)
get element calculations
Returns element calculations as object (요소 계산을 객체로 반환)
get screen calculations
Returns screen calculations as object (화면 계산을 객체로 반환)
get screen size
Returns screen size as object (화면 크기를 객체로 반환)
destroy
Destroys instance and removes all events (인스턴스를 파괴하고 모든 이벤트 제거)
Examples (예제)
Lazy Loading Images (이미지 지연 로딩)
Visibility는 일반적인 가시성 이벤트를 설정하기 위한 여러 단축키를 포함해요. type: 'image' 설정을 사용하면 이미지의 topVisible에 자동으로 이벤트를 연결해 data-src의 내용을 src로 로딩해요.
$('.demo.items .image img')
.visibility({
type : 'image',
transition : 'fade in',
duration : 1000
})
;
Elliot Fu (엘리엇 푸)
Add Friend (친구 추가)
View (보기)
Helen Troy (헬렌 트로이)
Add Friend (친구 추가)
View (보기)
Jenny Hess (제니 헤스)
Add Friend (친구 추가)
View (보기)
Veronika Ossi (베로니카 오시)
Add Friend (친구 추가)
View (보기)
Stevie (스티비)
Add Friend (친구 추가)
View (보기)
Steve Jobes (스티브 조브스)
Add Friend (친구 추가)
View (보기)
Ade (에이드)
Add Friend (친구 추가)
View (보기)
Chris (크리스)
Add Friend (친구 추가)
View (보기)
Joe Henderson (조 헨더슨)
Add Friend (친구 추가)
View (보기)
Laura (로라)
Add Friend (친구 추가)
View
Gradual Changes (점진적 변경)
각 콜백은 모든 계산된 값을 첫 번째 매개변수로 받으므로, 이를 사용해 요소를 조정할 수 있어요.
$('.changing.example .demo.segment')
.visibility({
once : false,
continuous : true,
onPassing : function(calculations) {
var newColor = 'rgba(0, 0, 0, ' + calculations.percentagePassed +')';
$(this)
.css('background-color', newColor)
;
}
})
;
once: false와 continuous: true로 설정하면 요소가 조건을 통과할 때마다 콜백이 계속 발생해요. 위 예제는 percentagePassed 값에 따라 배경색을 점진적으로 바꿔요.
Fixing Content To Viewport (콘텐츠를 뷰포트에 고정)
Visibility는 콘텐츠를 페이지 뷰포트에 붙이는 가벼운 방법을 제공해요. type: fixed를 사용하면 요소가 뷰포트를 지나간 후 fixed 클래스를 추가해요. 이 클래스 이름을 사용해 요소가 지나간 후 특별한 레이아웃 조건을 지정할 수 있어요.
$('.overlay.example .overlay')
.visibility({
type : 'fixed',
offset : 15 // give some space from top of screen
})
;
.visibility.example .overlay {
background-color: #FFFFFF;
padding: 0;
box-shadow: 0 0 0 rgba(0, 0, 0, 0);
transition: all 0.5s ease;
background: transparent;
}
/* change style */
.visibility.example .fixed.overlay {
position: fixed;
padding: 1em;
box-shadow: 0 0 6px rgba(0, 0, 0, 0.2);
}
Menu (메뉴)
Option 1 (옵션 1)
Option 2 (옵션 2)
Option 3 (옵션 3)
Infinite Scroll (무한 스크롤)
페이지네이션의 대안으로 onBottomVisible을 사용해 컨테이너의 하단에 도달했을 때 콘텐츠를 자동으로 로딩할 수 있어요.
$('.infinite.example .demo.segment')
.visibility({
once: false,
// update size when new content loads
observeChanges: true,
// load content on bottom edge visible
onBottomVisible: function() {
// loads a max of 5 times
window.loadFakeContent();
}
})
;
Infinite Scroll Example (무한 스크롤 예제)
Adding more content... (콘텐츠 추가 중...)
Settings (설정)
Functionality (기능)
가시성 동작을 설정하는 설정이에요.
Setting (설정)
Default (기본값)
Description (설명)
once
true
When set to false a callback will occur each time an element passes the threshold for a condition. (false로 설정하면 요소가 조건 임계값을 통과할 때마다 콜백이 발생)
continuous
false
When set to true a callback will occur anytime an element passes a condition not just immediately after the threshold is met. (true로 설정하면 임계값 충족 직후뿐 아니라 요소가 조건을 통과할 때마다 콜백이 발생)
type
false
Set to image to load images when on screen. Set to fixed to add class name fixed when passed. (image로 설정하면 화면에 있을 때 이미지를 로딩. fixed로 설정하면 지나갔을 때 fixed 클래스 이름 추가)
initialCheck
true
Whether visibility conditions should be checked immediately on init (초기화 시 가시성 조건을 즉시 확인할지 여부)
context
window
The scroll context visibility should use. (가시성이 사용할 스크롤 컨텍스트)
refreshOnLoad
true
Whether visibility conditions should be checked on window load. This ensures that after images load content positions will be updated correctly. (window load 시 가시성 조건을 확인할지 여부. 이미지 로드 후 콘텐츠 위치가 올바르게 업데이트되도록 함)
refreshOnResize
true
Whether visibility conditions should be checked on window resize. Useful when content resizes causes continuous changes in position (window resize 시 가시성 조건을 확인할지 여부. 콘텐츠 크기 변경이 위치의 지속적인 변화를 일으킬 때 유용)
checkOnRefresh
true
Whether visibility conditions should be checked on calls to refresh. These calls can be triggered from either resize, load or manually calling $('.foo').visibility('refresh') (refresh 호출 시 가시성 조건을 확인할지 여부. 이 호출은 resize, load 또는 수동으로 $('.foo').visibility('refresh')를 호출해 트리거될 수 있음)
zIndex
1
Specify a z-index when using type: 'fixed'. (type: 'fixed' 사용 시 z-index 지정)
offset
0
Value that context scrollTop should be adjusted in pixels. Useful for making content appear below content fixed to the page. (context의 scrollTop을 픽셀로 조정할 값. 페이지에 고정된 콘텐츠 아래에 콘텐츠가 나타나도록 할 때 유용)
includeMargin
false
Whether element calculations should include its margin (요소 계산에 마진을 포함할지 여부)
throttle
false
When set to an integer, scroll position will be debounced using this ms value. false will debounce with requestAnimationFrame. (정수로 설정하면 이 ms 값으로 스크롤 위치를 디바운스. false는 requestAnimationFrame으로 디바운스)
observeChanges
true
Whether to automatically refresh content when changes are made to the element's DOM subtree (요소의 DOM 하위 트리에 변경이 있을 때 콘텐츠를 자동으로 새로고침할지 여부)
transition
false
When using type: image allows you to specify transition when showing a loaded image (type: image 사용 시 로딩된 이미지를 보여줄 때 트랜지션 지정 가능)
duration
1000
When using type: image allows you to specify transition duration (type: image 사용 시 트랜지션 시간 지정 가능)
Visibility Callbacks (가시성 콜백)
이름 있는 가시성 이벤트에서 발생하는 콜백이에요.
Context (컨텍스트)
Description (설명)
onTopVisible
$element
Element's top edge has passed bottom of screen (요소의 상단 가장자리가 화면 하단을 지나감)
onTopPassed
$element
Element's top edge has passed top of the screen (요소의 상단 가장자리가 화면 상단을 지나감)
onBottomVisible
$element
Element's bottom edge has passed bottom of screen (요소의 하단 가장자리가 화면 하단을 지나감)
onPassing
$element
Any part of an element is visible on screen (요소의 일부가 화면에 보임)
onBottomPassed
$element
Element's bottom edge has passed top of screen (요소의 하단 가장자리가 화면 상단을 지나감)
onTopVisibleReverse
$element
Element's top edge has not passed bottom of screen (요소의 상단 가장자리가 화면 하단을 지나지 않음)
onTopPassedReverse
$element
Element's top edge has not passed top of the screen (요소의 상단 가장자리가 화면 상단을 지나지 않음)
onBottomVisibleReverse
$element
Element's bottom edge has not passed bottom of screen (요소의 하단 가장자리가 화면 하단을 지나지 않음)
onPassingReverse
$element
Element's top has not passed top of screen but bottom has (요소 상단은 화면 상단을 지나지 않았지만 하단은 지나감)
onBottomPassedReverse
$element
Element's bottom edge has not passed top of screen (요소의 하단 가장자리가 화면 상단을 지나지 않음)
Image Callbacks (이미지 콜백)
type: 'image'를 사용할 때만 발생하는 콜백이에요.
Context (컨텍스트)
Description (설명)
onLoad
img
Occurs after an image has completed loading (이미지 로딩이 완료된 후 발생)
onAllLoaded
last loaded img
Occurs after all img initialized at the same time have loaded. (동시에 초기화된 모든 이미지가 로딩된 후 발생)
Fixed Callbacks (고정 콜백)
type: 'fixed'를 사용할 때만 발생하는 콜백이에요.
Context (컨텍스트)
Description (설명)
onFixed
$element
Occurs after element has been assigned position fixed (요소에 position: fixed가 할당된 후 발생)
onUnfixed
$element
Occurs after element has been removed from fixed position (요소가 fixed 위치에서 제거된 후 발생)
Utility Callbacks (유틸리티 콜백)
이름 있는 가시성 이벤트에서 발생하는 콜백이에요.
Context (컨텍스트)
Description (설명)
onUpdate(calculations)
$element
Occurs each time an elements calculations are updated (요소의 계산이 업데이트될 때마다 발생)
onRefresh
$element
Occurs whenever element's visibility is refreshed (요소의 가시성이 새로고침될 때마다 발생)
DOM Settings (DOM 설정)
DOM 설정은 이 모듈이 DOM과 어떻게 인터페이스할지 지정해요.
Setting (설정)
Default (기본값)
Description (설명)
namespace
visibility
Event namespace. Makes sure module teardown does not effect other events attached to an element. (이벤트 네임스페이스. 모듈 해제가 요소에 연결된 다른 이벤트에 영향을 주지 않도록 해요.)
className
className : {
fixed : 'fixed',
}
Class names used to attach style to state (상태에 스타일을 연결하는 데 사용되는 클래스 이름)
Debug Settings (디버그 설정)
디버그 설정은 콘솔로의 디버그 출력을 제어해요.
Setting (설정)
Default (기본값)
Description (설명)
name
Visibility
Name used in debug logs (디버그 로그에 사용되는 이름)
silent
false
Silences all console output including error messages, regardless of other debug settings. (다른 디버그 설정과 무관하게 오류 메시지를 포함한 모든 콘솔 출력을 조용히 해요.)
debug
false
Provides standard debug output to console (콘솔에 표준 디버그 출력 제공)
performance
true
Provides standard debug output to console (콘솔에 표준 디버그 출력 제공)
verbose
true
Provides ancillary debug output to console (콘솔에 보조 디버그 출력 제공)
errors
error : {
method : 'The method you called is not defined.',
}
더 알아보기 (Learn more)
Visibility는 스크롤 기반 UI 패턴의 핵심 동작이에요. onPassed 그룹 이벤트로 콘텐츠 읽힘 퍼센트를 추적하고, type: 'image'로 이미지 지연 로딩을 쉽게 적용할 수 있으니 필요에 맞게 조합해 보세요.