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.
$(document).scroll(function() { var cutoff = $(window).scrollTop(); $('div').each(function(){ if($(this).offset().top + $(this).height() > cutoff){ $('div').removeClass('current'); $(this).addClass('current'); var currSection = $(this).attr('id'); console.log(currSection); if ($('.circle li').data('id') == currSection) { }; return false; } }); });
ul{ position:fixed; z-index:9; top:0; } .active{ color:red; } div{ height:500px; } div:nth-child(odd){ background:green; } div:nth-child(even){ background:blue; }
<div id="home"></div> <div id="who"></div> <div id="team"></div> <div id="why"></div> <div id="contact"></div> <ul class="circle"> <li data-id="home" class="active">a</li> <li data-id="who">b</li> <li data-id="team">c</li> <li data-id="why">d</li> <li data-id="contact">f</li> </ul>
Advertisement
Answer
Change scroll event listener to this
$(document).scroll(function () { var cutoff = $(window).scrollTop(); $('div').each(function () { if ($(this).offset().top + $(this).height() > cutoff) { $('div').removeClass('current'); $(this).addClass('current'); var currSection = $(this).attr('id'); console.log(currSection); $('li').removeClass('active'); $('li[data-id=' + currSection + ']').addClass('active'); return false; } }); });