WebPublisher/JavaScript & jQuery

[js] 각 section에 스크롤 진입 시 .active 클래스명 삽입 scroll 감지 event

amanda 2024. 8. 29. 16:43

html

<div class="event_contents">
	<div id="sec_01" class="event_sec event_sec_01">
    	<div class="inner">
        	<div class="item item_01">
            	<!-- item 01 contents -->
            </div>
        	<div class="item item_02">
            	<!-- item 02 contents -->
            </div>
        </div>
    </div>
	<div id="sec_02" class="event_sec event_sec_02">
    	<div class="inner">
        	<div class="item item_03">
            	<!-- item 03 contents -->
            </div>
        	<div class="item item_04">
            	<!-- item 04 contents -->
            </div>
        </div>
    </div>
</div>

 

 

javaScript

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');
			}
		})
	})
}