menu-scroll

menu-scroll

by Boba Poshtar

HTML

<nav>
		<menu>
			<li><a href="#section1">Section 1</a></li>
			<li><a href="#section2">Section 2</a></li>
			<li><a href="#section3">Section 3</a></li>
			<li><a href="#section4">Section 4</a></li>
			<li><a href="#section5">Section 5</a></li>
			<li><a href="#footer">Footer</a></li>
		</menu>
	</nav>
	
	<section id="section1"><h2>Section 1</h2></section>
	<section id="section2"><h2>Section 2</h2></section>
	<section id="section3"><h2>Section 3</h2></section>
	<section id="section4"><h2>Section 4</h2></section>
	<section id="section5"><h2>Section 5</h2></section>
	<footer id="footer">
		<h2>Contacts</h2>
		<p>&copy; Copyright 1917-2017</p>
	</footer>

CSS

body { margin: 0; padding-top: 50px; }
		section {
			padding: 1px 40px;
			height: 100vh;
			border-bottom: 1px solid silver;
		}
		nav {
			position: fixed;
			z-index: 9000;
			left: 0;
			right: 0;
			top: 0;
			background: #ffd;
			box-shadow: 0 10px 20px rgba(0, 0, 0, 0.5);
		}
		menu { margin: 0; padding: 0; }
		menu li { display: inline-block; list-style: none; }
		menu a { display: block; padding: 16px 24px; }
		menu li a:hover { color: orange; }
		menu li.active a { color: red; }

JavaScript

(function($){

	$('menu a[href^="#"]').on('click', function(){
		$('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top - 50 }, 2000);
	});
	setLiActive();
	$(window).on('scroll', setLiActive);


	function setLiActive(){
		let $a = $('menu a[href^="#"]');
		$a.parent().removeClass('active');
		let n = $a.length;
		let h = $(window).height() / 2;
		let i;
		for (i = 0; i < n; i++){

			if ($(window).scrollTop() - h < $($a.eq(i).attr('href')).offset().top) break; 
		}
		$a.eq(i).parent().addClass('active');
	}

})(jQuery);