Internet/jQuery

스크롤 내리면 나타나는 제이쿼리 탑버튼

by 1730 2014. 10. 14.

블로그나 사이트에 장문을 글을 읽을 때 스크롤이 많이 내려갔는데 다른 메뉴를 이용하기 위해 스크롤을 키보드의 Home키로 한 번에 올릴 수도 있지만 마우스를 클릭하여 한번에 사이트 탑 위치로 이동하는 jQuery 소스입니다.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

탑버튼을 사용하기 위해서 jquery.min.js 설치되어 있어야 하고 탑 버튼 소스는 위 코드보다 아래에 있어야만 정상 작동됩니다.

 

<script type=text/javascript> 
$(document).ready(function(){
	$(".return-top").hide(); // 탑 버튼 숨김 	
	$(function () {
		$(window).scroll(function () {
			if ($(this).scrollTop() > 100) { // 스크롤 내릴 표시
				$('.return-top').fadeIn();
			}else {
				$('.return-top').fadeOut();
			}
		});     
		$('.return-top').click(function () {
			$('body,html').animate({
				scrollTop: 0
			}, 800);  // 탑 이동 스크롤 속도
				return false;
		});
	});
});	
</script>
<a class="return-top" href="#" style="right:15px; bottom:15px; position:fixed; z-index:9999;">[	RETURN TOP ]</a>

제이쿼리 소스는 <Haed>에 넣고 a 태그는 다른 곳에 따로따로 배치해도 되고 position:fixed;로 브라우저를 위치 잡기 때문에 두 코드를 같이 <Haed>등 어느 위치에 넣더라고 적용이 됩니다.