There is such a smooth page navigation. How do I add the "current" class to the navigation menu, depending on where the user is now? So that when a person gradually turns the mouse, a section of the site in the navigation menu is displayed to him. https://jsfiddle.net/sazdan/h9rske5p/
$(document).ready(function(){
$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
let target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
<h2 id="one">One</h2>
<p> Lorem Ipsum</p>
<h2 id="two">Two</h2>
<p>Lorem Ipsum.</p>
<h2 id="three">Three</h2>
<p>Lorem Ipsum</p>
<h2 id="four">Four</h2>
<p>Lorem Ipsum</p>
<h2 id="five">Five</h2>
<p>Lorem Ipsum</p>
<h2 id="six">Six</h2>
<p>Lorem Ipsum</p>
</div>
<aside>
<ul>
<li><a class="current" href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>
<li><a href="#four">Four</a></li>
<li><a href="#five">Five</a></li>
<li><a href="#six">Six</a></li>
</ul>
</aside>
CodePudding user response:
I am not quite sure if this is what you're trying to achieve, but you can place a scroll
event in window
to calculate which h2
is within screen bounds and set the current
class to the respective a
:
$(window).on('scroll', function(){
let viewportTop = $(window).scrollTop();
let viewportBottom = viewportTop $(window).height();
$('h2').each(function(){
let elementTop = $(this).offset().top;
let elementBottom = elementTop $(this).outerHeight();
if(elementBottom > viewportTop && elementTop < viewportBottom){
$('aside a').removeClass('current');
$('aside a[href="#' $(this).attr('id') '"]').addClass('current');
}
});
});
Add this inside $(document).ready()
.
You can check this article on how to detect if an element is on screen.