Brief
Use$(this).offset().top
instead of $(this).position().top
As
.position()
get the current coordinates of the first element in the set of matched elements, relative to the offset parent whereas .offset()
get the current coordinates of the first element in the set of matched elements, relative to the document.
In your website all the DIV with class inside
.target
are inside therefore all the element of class .target
are returning the value .position().top
equal to 0.
Decrease the offset value so that the
class
change when element reach the menu by making the if
condition like this:if($(window).scrollTop() >= $(this).offset().top - $("#cssmenu").height())
HTML
<section id="main"><div class="target" id="1">TARGET 1</div>
<div class="target" id="2">TARGET 2</div>
<div class="target" id="3">TARGET 3</div>
<div class="target" id="4">TARGET 4</div>
</section>
<aside id="nav">
<nav>
<a href="#1" class="active">Punkt 1</a>
<a href="#2">Punkt 2</a>
<a href="#3">Punkt 3</a>
<a href="#4">Punkt 4</a>
</nav>
</aside>
CSS
* {margin: 0;
padding: 0;
}
#main {
width: 75%;
float: right;
}
#main div.target {
background: #ccc;
height: 400px;
}
#main div.target:nth-child(even) {
background: #eee;
}
#nav {
width: 25%;
position: relative;
}
#nav nav {
position: fixed;
width: 25%;
}
#nav a {
border-bottom: 1px solid #666;
color: #333;
display: block;
padding: 10px;
text-align: center;
text-decoration: none;
}
#nav a:hover, #nav a.active {
background: #666;
color: #fff;
}
jQuery
$('#nav nav a').on('click', function(event) {$(this).parent().find('a').removeClass('active');
$(this).addClass('active');
});
$(window).on('scroll', function() {
$('.target').each(function() {
if($(window).scrollTop() >= $(this).offset().top) {
var id = $(this).attr('id');
$('#nav nav a').removeClass('active');
$('#nav nav a[href=#'+ id +']').addClass('active');
}
});
});
Comments
Post a Comment