Korean English Japanese

탑버튼(topbtn) DOM 위치값 계산

탑버튼(topbtn) DOM 위치값 계산

$(function(){
        var thisTopButton = $('.btn_top');

        $(window).on('scroll',function(){
            var thisScrollTop = $(this).scrollTop(),
            thisWindowHeight = $(this).height(),
            thisPageHeight = $('#wrap').height(),
            thisFooterHeight = $('#footer').height(),
            btnFixedPoint = 0;

            btnFixedPoint = thisPageHeight - (thisWindowHeight + (thisFooterHeight));

            if (thisScrollTop >= btnFixedPoint) {
                thisTopButton.addClass('btn_fixed');
            } else {
                thisTopButton.removeClass('btn_fixed');
            }
        });
        thisTopButton.find('a').on('click',function(event){
            event.preventDefault();
            $('html, body').animate({scrollTop: '0'}, 300);
        });
    });

JQuery로 쉽게 구현하는 탑버튼

.on 메서드 : 현재 또는 미래에 존재하는 요소에 대해서 이벤트를 적용하여 처리할 수 있다. .on('Scroll') 스크롤을 처리했을 시, 변수값(Var)으로 .scrollTop(), .height()의 메서드를 사용하여 값을 처리한다. btnFixedPoint = thisPageHeight - (thiswindowHeight + (thisFooterHeight));

조건문 클래스 추가

만약, Footer에서 thisScrollTop의 값이 btnFixedPoint보다 클 경우 'btn_fixed' 클래스를 추가한다.(.addClass 메서드 적용) 아닐 경우, 제거한다.(if or else)

thisTopButton이 .find 메서드로 ('a')태그를 찾는다. 그다음, .on('click') 클릭이벤트 발생시, 'html, body' 부분까지 .animate 메서드로 자연스럽게 scrollTop을 적용한다. 이때, scrollTop의 값은 '0'이므로, '0'만큼 이동한다. 속도는 0.3의 값으로 애니메이션 효과가 적용된다.