$.fn.inView = function(){
//Window Object
var win = $(window);
//Object to Check
obj = $(this);
//the top Scroll Position in the page
var scrollPosition = win.scrollTop();
//the end of the visible area in the page, starting from the scroll position
var visibleArea = win.scrollTop() + win.height();
//the end of the object to check
var objEndPos = (obj.offset().top + obj.outerHeight());
return(visibleArea >= objEndPos && scrollPosition <= objEndPos ? true : false)
};
$(window).scroll(function(){
if($("#homepage").inView()) {
//#homepage active
} else if($("#connections").inView()) {
//#connections active
}
});
Add class=active on scroll
-
15-07-2023 - |
Вопрос
I have a one page website with a fixed header and some sections.
I am using scrollTo and localScroll to jump to each section, but I have a problem to add class=active
to a href
on scroll.
I can add class=active
on click, but I do not know how to do it on scroll and obviously remove it when switching from "old" to "new" section.
This is what I have done, when clicking:
$('#menu').find('a').click(selectNav);
function selectNav() {
$(this).parents('ul:first').find('a').removeClass('active').end().end().addClass('active');
}
function trigger(data) {
var el = $('#menu').find('a[href$="' + data.id + '"]').get(0);
selectNav.call(el);
}
UPDATE:
<ul id="menu">
<li><a href="#homepage"><span>Home</span></a></li>
<li><a href="#connections"><span>Connections</span></a></li>
</ul>
<section id="homepage" class="main">
..........
</section>
<section id="connections" class="main">
..........
</section>
Any help, please?
Решение 2
Другие советы
If I read your question correct, you want to add the class, then make the window scroll to a certain position, and then remove the class when the scrolling is done.
You could take a look at this question: jQuery scroll to element
And then my suggestion would be apply the "Active" class on click, and then remove it again, once the animation is completed, using the callback function.
$("body").animate(
{
scrollTop:$("#connections").offset().top},0, function(){
console.log("Done - Remove class")}
}
)
This is the only solution I could come up with, that will remove the class AFTER the scrolling is completed.