[javascript] 화면 스크롤시 사이드 메뉴 색상 변경하기

이번 포스팅에서 화면을 스크롤시 사이드 메뉴의 색상이 자동으로 변경되는 소스를 알아보겠습니다.

해당 영역에 넘어가면 사이드 메뉴에서도 색이 변하면서 반응하고 사이드 메뉴를 클릭시 해당 위치로 이동하는 소스입니다.

 

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>스크롤 사이드 메뉴 색상 변경</title>
</head>
<body>
    <div class="sidebar">
        <div class="menu-item" data-target="content1">Section 1</div>
        <div class="menu-item" data-target="content2">Section 2</div>
        <div class="menu-item" data-target="content3">Section 3</div>
        <div class="menu-item" data-target="content4">Section 4</div>
    </div>
    <div class="content">
        <section id="content1">Content 1</section>
        <section id="content2">Content 2</section>
        <section id="content3">Content 3</section>
        <section id="content4">Content 4</section>
    </div>
</body>
</html>

 

CSS

body {
    	margin: 0;
    	font-family: Arial, sans-serif;
}

.sidebar {
	width: 200px;
	background-color: #f4f4f4;
	position: fixed;
	top:50%;
	right:0;
	transform:translateY(-50%);
}

.menu-item {
	padding: 15px;
	margin: 5px 0;
	cursor: pointer;
}

.menu-item.active {
	background-color: #007BFF;
	color: white;
}

.content {
	flex-grow: 1;
}

section {
	height: 100vh; /* 높이를 충분히 크게 설정 */
	background: #f0f0f0; /* 가시성을 위해 배경색 추가 */
    	text-align: center;
    	line-height: 100vh;
}

 

javascript

document.addEventListener('DOMContentLoaded', function() {
	const menuItems = document.querySelectorAll('.menu-item');
	const sections = document.querySelectorAll('section');

    	function changeActiveMenuItem() {
    		let index = sections.length;

       	 	while (--index && window.scrollY + 50 < sections[index].offsetTop) {}

        	menuItems.forEach((menuItem) => menuItem.classList.remove('active'));
        	if (index >= 0) {
        		menuItems[index].classList.add('active');
    		}
	}

    	changeActiveMenuItem();
   	window.addEventListener('scroll', changeActiveMenuItem);

    	menuItems.forEach(item => {
   		item.addEventListener('click', () => {
        		const target = document.getElementById(item.getAttribute('data-target'));
            		window.scrollTo({
            			top: target.offsetTop,
                		behavior: 'smooth'
           		});
        	});
	});
});

 

미리보기

 

'코딩 > Javascript' 카테고리의 다른 글

스크롤을 이용한 이미지 애니메이션  (1) 2024.08.28