WebPublisher/JavaScript & jQuery

[jQuery] scroll 시 해당 section에 active 클래스 추가

amanda 2024. 11. 14. 17:37

HTML

<div id="sec_01">
	<div class="item item_01">
    </div>
    <div class="item item_02">
    </div>
    <div class="item item_03">
    </div>
</div>

 

CSS

/* .active 클래스명 주고 애니메이션 스타일링, 아래는 예시 */
.item_01.active .item_btm .con_wrap:before{
	animation: triangleChartArrow 0.5s 1.5s linear forwards;
}
.item_01.active .chart_wrap:before{
	animation: triangleChart 1s 0.5s linear forwards;
}
.item_01.active .chart_wrap:after{
	animation: triangleChartTxt 1.5s 2s linear infinite;
	opacity: 1;
	-webkit-transition: opacity 0.5s 2s;
	transition: opacity 0.5s 2s;
}

@keyframes triangleChartArrow{
	to{width: 255px;}
}
@keyframes triangleChart{
	to{width: 100%;}
}
@keyframes triangleChartTxt{
	0%, 100%{-webkit-transform: scale(1);transform: scale(1);}
	50%{-webkit-transform: scale(1.2);transform: scale(1.2);}
}

 

jQuery

function secScroll(){
	const screenHeight = document.documentElement.clientHeight;
	$(window).scroll(function(){
		$('.item').each(function(){
			let crtHeight = $(window).scrollTop(); // current scroll top
			let targetSec = $(this); // target
			// let targetSec = $('.item_0' + i); // target

			let secStart = targetSec.offset().top; // target top
			let secHeight = targetSec.innerHeight(); // target height

			let targetStart = secStart - (screenHeight * 0.7); // event start point
			let targetEnd = targetStart + secHeight + (screenHeight * 0.5); // event end point

			if(targetStart < crtHeight){
				targetSec.addClass('active');
			}
			if(crtHeight < targetStart || targetEnd < crtHeight){
				targetSec.removeClass('active');
			}
		})
	})
}