Tags

, , ,

My Navigation

<header>
	<nav>
		<ul>
			<li><a class="active" href="#home">Home</a></li>
			<li><a href="#about">About</a></li>
			<li><a href="#services">Services</a></li>
			<li><a href="#contact">Contact</a></li>
		</ul>
	</nav>
</header>

Content Section


<div class="content">
	<section id="home"></section>
	<section id="about"></section>
	<section id="services"></section>
	<section id="contact"></section>
</div>

Some styling using css

html, body { margin: 0; padding: 0; width: 100%; height: 100%; }
header { position: fixed; top: 0; width: 100%; height: 80px; background: #fff; }
nav { width: 960px; height: 80px; margin: 0 auto; }
nav ul { margin: 20px 0 0; }
nav ul li { display: inline-block; margin: 0 30px 0 0; }
a { color: #4D4D4D; font-family: sans-serif; text-transform: uppercase; text-decoration: none; line-height: 42px; }
.active { color: #2dbccb; }
.content { width: 100%; height: 100%; }
.content > section { width: 100%; height: 100%; }
#home { background: #2dbccb; }
#about { background: #f6c362; }
#services { background-color: #eb7e7f; }
#contact { background-color: #415c71; }

Now time for some jquery

$(document).ready(function () {
	$(document).on("scroll", onScroll);
	
	// Trigger Click to go specific section or add active
	$('a[href^="#"]').on('click', function (e) {
		e.preventDefault();
		$(document).off("scroll");

		$('a').each(function () {
			$(this).removeClass('active');
		})
		$(this).addClass('active');

		var target = this.hash;
		$target = $(target);
		
		// Scrolling 
		$('html, body').stop().animate({
			'scrollTop': $target.offset().top+2
		}, 500, 'swing', function () {
			window.location.hash = target;
			$(document).on("scroll", onScroll);
		});
	});
});

function onScroll(event){
	var scrollPosition = $(document).scrollTop();
	
	// set your navigation a class name
	$('nav a').each(function () {
		var currentLink = $(this);
		var refElement = $(currentLink.attr("href"));
		if (refElement.position().top <= scrollPosition && refElement.position().top + refElement.height() > scrollPosition) {
			$('nav ul li a').removeClass("active");
			currentLink.addClass("active");
		}
		else{
			currentLink.removeClass("active");
		}
	});
}

Working Example

Advertisements