when i scroll the page, i want to add class active menu item. i can get the current div id like this var currSection = $(this).attr(‘id’). im stuck with id and data-id matching. here is the codes. ty for helping guys.
JavaScript
x
23
23
1
$(document).scroll(function() {
2
3
var cutoff = $(window).scrollTop();
4
5
$('div').each(function(){
6
if($(this).offset().top + $(this).height() > cutoff){
7
$('div').removeClass('current');
8
$(this).addClass('current');
9
10
var currSection = $(this).attr('id');
11
12
console.log(currSection);
13
14
if ($('.circle li').data('id') == currSection) {
15
16
};
17
18
return false;
19
20
21
}
22
});
23
});
JavaScript
1
17
17
1
ul{
2
position:fixed;
3
z-index:9;
4
top:0;
5
}
6
.active{
7
color:red;
8
}
9
div{
10
height:500px;
11
}
12
div:nth-child(odd){
13
background:green;
14
}
15
div:nth-child(even){
16
background:blue;
17
}
JavaScript
1
13
13
1
<div id="home"></div>
2
<div id="who"></div>
3
<div id="team"></div>
4
<div id="why"></div>
5
<div id="contact"></div>
6
7
<ul class="circle">
8
<li data-id="home" class="active">a</li>
9
<li data-id="who">b</li>
10
<li data-id="team">c</li>
11
<li data-id="why">d</li>
12
<li data-id="contact">f</li>
13
</ul>
Advertisement
Answer
Change scroll event listener to this
JavaScript
1
24
24
1
$(document).scroll(function () {
2
3
var cutoff = $(window).scrollTop();
4
5
$('div').each(function () {
6
if ($(this).offset().top + $(this).height() > cutoff) {
7
$('div').removeClass('current');
8
$(this).addClass('current');
9
10
var currSection = $(this).attr('id');
11
12
console.log(currSection);
13
14
$('li').removeClass('active');
15
$('li[data-id=' + currSection + ']').addClass('active');
16
17
18
return false;
19
20
21
}
22
});
23
});
24