Question:
Tell me how to make a horizontal menu in a certain section (in the middle of the landing page), when it reaches the top of the page, it becomes fixed (sticking to the top), and all the rest of the content goes under it; and after the end of the section in which the menu is located, the fixing was disabled and the menu scrolled further …
Answer:
- put two "marks": at the beginning of the section and at the end
- Create a scroll event that calculates the position of the page and enables or disables fixing.
I suggest this option:
function stickMenu() {
var windowTop = $(window).scrollTop();
var sectionStarts = $('#sectionStarts').offset().top;
var sectionEnds = $('#sectionEnds').offset().top;
if (windowTop > sectionEnds) {
$('.menu').removeClass('fixed');
} else if (windowTop > sectionStarts) {
$('.menu').addClass('fixed');
} else {
$('.menu').removeClass('fixed');
}
}
$(window).scroll(function() {
stickMenu();
});
div:not(.menu) {
height: 300px;
}
.menu {
background-color: lightgray;
}
.menu.fixed {
position: fixed;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Начало страницы</div>
<div class="menu">
<a href="#">menu item 1</a>
<a href="#">menu item 2</a>
<a href="#">menu item 3</a>
<a href="#">menu item 4</a>
<a href="#">menu item 5</a>
<a href="#">menu item 6</a>
</div>
<span id="sectionStarts"></span>
<div>Начало секции</div>
<div>Содержимое секции</div>
<span id="sectionEnds"></span>
<div>конец секции</div>
<div>Конец страницы</div>