Home » , , , » JQuery: Mini WayPoints

JQuery: Mini WayPoints

Mini WayPoints

Kode ini dibuat berdasarkan efek plugin JQuery WayPoints, meskipun Saya tidak tahu apakah plugin WayPoints berisi seperti ini atau tidak. Di sini Saya cuma mengambil ciri khasnya yang menarik: Setiap item navigasi terkait akan berubah warna saat seksi yang menjadi tujuannya mencapai tempat yang tepat.

Markupnya cuma terdiri dari sebuah elemen <nav> dan beberapa elemen <section> dengan ID yang ditentukan berdasarkan hash pada masing-masing tautan:

HTML

<nav>
<li><a href='#home'>Home</a></li>
<li><a href='#about'>About</a></li>
<li><a href='#portfolio'>Portfolio</a></li>
<li><a href='#contact'>Contact</a></li>
</nav>
<section id='home'> ... </section>
<section id='about'> ... </section>
<section id='portfolio'> ... </section>
<section id='contact'> ... </section>

CSS

nav {
position:fixed !important;
position:absolute;
top:0;
right:0;
left:0;
z-index:77;
}

nav ul {
margin:0 0;
padding:0 0;
background-color:black;
height:30px;
overflow:hidden;
}

nav li {
list-style:none;
margin:0 0;
padding:0 0;
float:left;
display:inline;
}

nav a {
font:bold 11px/30px Arial,Sans-Serif;
color:white;
display:block;
padding:0 15px;
text-decoration:none;
}

nav a:hover {color:#ccc;}
nav a.active {background-color:darkblue;}

section {
padding:30px;
border-top:2px solid darkred;
height:1000px;
}

#home {margin-top:30px;background-color:green;}
#about {background-color:skyblue;}
#portfolio {background-color:gray;}
#contact {background-color:orange;}

JQuery

$(function() {
var navHeight = $('nav').outerHeight();
$('nav a').on("click", function() {
var hash = this.hash,
target = $(hash).offset().top - navHeight;
// Smooth scrolling...
$('html,body').stop().animate({
scrollTop: target
}, 1500, function() {
window.location.hash = hash;
$(window).scrollTop($(hash).offset().top - navHeight);
});
return false;
});
$(window).on("scroll resize", function() {
$('nav a').each(function() {
var section = this.hash,
sectionTop = $(section).offset().top,
windowTop = $(window).scrollTop() + navHeight,
sectionEnd = sectionTop + $(section).outerHeight() - navHeight;
// Add or remove active class based on the section relating to the navigation
if ((windowTop >= sectionTop) && (windowTop <= sectionEnd)) {
$(this).closest('nav').find('.active').removeClass('active');
$(this).addClass('active');
} else {
$(this).removeClass('active');
}
});
}).trigger("scroll");

// Scroll to section ID based on window.location.hash
// The 'navHeight' was only used to add the jump spacing.
if (window.location.hash) {
var hash = window.location.hash;
$(window).scrollTop($(hash).offset().top - navHeight);
}

});

0 komentar:

Posting Komentar