본문 바로가기
Spring/JavaScript+Jsp(HTMl)

[JavaScript/JQuery] Top(맨 위) & Bottom(맨 아래) 스크롤 공통 기능 만들기

by snow_hong 2023. 4. 7.

 

자바스크립트로 Top(맨 위 / 최상단) & Bottom(맨 아래 / 최하단) 스크롤 이동 시키기 기능을 공통으로 만드는 예제에 대해서 알아보자!

 

웹을 하다보면 편의성을 위해서 최상단과 최하단 버튼을 만들어서 스크롤을 이동시키고 싶다.

그리고 나는 해당 기능이 필요없을 경우(ex. 최상단 스크롤에 위치하면 top버튼 필요없음)에 버튼이 표시되고 싶지 않았다.

 

이제 예제 코드를 보고 알아보자!

 

[ 예제 ]

- bottombutton.js (최하단 / 맨아래로 js)

(function($){
$.bottombutton = function(op){
    var _op = {
        html : "",               //String (Html Code)
        css : undefined,            //String (Css Code)
        //css : "background: red;",            //String (Css Code)
        scrollSpeed : 150,          //Number (Default : 150)
        scrollAndShow : false      //boolean (Default : false)
    }
    for(key in op){ _op[key] = op[key]; }



    var basicCSS = {
            width : '40px',
            height : '40px',
            background : 'url(/images/btn_bottom.png) 0 0 no-repeat',
            left : '97%',
            bottom: '16px',
            border : '0'
    };
    if(_op.css != undefined){
        var userCss  = {};
        var arr = (_op.css||'').split(";").filter(function(n){ return n != "" });
        for(key in arr){
            var index = arr[key].split(":");
            var uKey = index[0].replace(/(\s*)/g,"");
            var uValue = index[1].replace(/(\s*)/g,"");
            userCss[uKey] = uValue;
        }
        for(key in userCss){ basicCSS[key] = userCss[key]; }
    }
    var attr = "";
    for(key in basicCSS){ attr += key+':'+basicCSS[key]+'; '; }



    var scrollAndShow ="";
    if(_op.scrollAndShow){
        scrollAndShow ="display:none;";
        var px = $(document).height()-$(window).height();
        var on = true;
        $(window).scroll(function(){
        	px = $(document).height()-$(window).height();
            if($(this).scrollTop() < px){ 
            	if(!on){$('#bottomButton').fadeIn(); on = true;} 
            }else{ if(on){$('#bottomButton').fadeOut(); on = false;} }
        });
        if($(window).scrollTop() < px){ scrollAndShow = "display:block;"; }
    }



    var html = '<button type="button" id="bottomButton" style="'+scrollAndShow+'position:fixed; border:none; outline:none; overflow:hidden; cursor:pointer; '+attr+'">'+_op.html+'</button>';
    $('body').append(html);



    $('#bottomButton').click(function(){
        $('html, body').animate({scrollTop : $(document).height()}, parseInt(_op.scrollSpeed));
    });
};
})(jQuery);

 

- topbutton.js (최상단 버튼 / 맨위로 js)

(function($){
$.topbutton = function(op){
    var _op = {
        html : "",               //String (Html Code)
        css : undefined,            //String (Css Code)
        scrollSpeed : 150,          //Number (Default : 150)
        scrollAndShow : false      //boolean (Default : false)
    }
    for(key in op){ _op[key] = op[key]; }



    var basicCSS = {
            width : '40px',
            height : '40px',
            background : 'url(/images/btn_top.png) 0 0 no-repeat',
            left : '1104px',
            bottom: '60px',
            border : '0'
    };
    if(_op.css != undefined){
        var userCss  = {};
        var arr = _op.css.split(";").filter(function(n){ return n != "" });
        for(key in arr){
            var index = arr[key].split(":");
            var uKey = index[0].replace(/(\s*)/g,"");
            var uValue = index[1].replace(/(\s*)/g,"");
            userCss[uKey] = uValue;
        }
        for(key in userCss){ basicCSS[key] = userCss[key]; }
    }
    var attr = "";
    for(key in basicCSS){ attr += key+':'+basicCSS[key]+'; '; }



    var scrollAndShow ="";
    if(_op.scrollAndShow){
        scrollAndShow ="display:none;";
        var px = 100;
        var on = true;
        $(window).scroll(function(){
            if($(this).scrollTop() > px){ if(!on){$('#topButton').fadeIn(); on = true;} }
            else{ if(on){$('#topButton').fadeOut(); on = false;} }
        });
        if($(window).scrollTop() > px){ scrollAndShow = "display:block;"; }
    }



    var html = '<button type="button" id="topButton" style="'+scrollAndShow+'position:fixed; border:none; outline:none; overflow:hidden; cursor:pointer; '+attr+'">'+_op.html+'</button>';
    $('body').append(html);



    $('#topButton').click(function(){
        $('html, body').animate({scrollTop : 0}, parseInt(_op.scrollSpeed));
    });
};
})(jQuery);

 

- layout.jsp (공통으로 사용하는 jsp)

....
<script src="/js/topbutton.js"></script>
<script src="/js/bottombutton.js"></script>

....

<script type="text/javascript">

	//Top Button
	$.topbutton({
	    scrollAndShow : true,    //Boolean
	    scrollSpeed : 150         //Number
	});
	

//만약 해당 jsp만 위치를 변경할 경우 css로 해당 버튼 위치 변경
	// $('#topButton').css('left','97%'); 
	
	//bottom Button
	$.bottombutton({
	    scrollAndShow : true,    //Boolean
	    scrollSpeed : 150         //Number
	});
	
</script>

 

[예제 결과]

최상단 모습

최상단일땐 top버튼이 필요없어 bottom버튼만 생성된다.

중간부분

jsp의 중간엔 top버튼과 bottom버튼이 생성된다.

 

최하단

최하단경우 bottom버튼이 필요없어 top버튼만 생성된다.

 

예제코드와 같이하면 공통적으로 모든페이지마다 맨위로 맨아래 버튼이 생성된다.

 

728x90

댓글