html – Fixing the menu when it comes to the top, and disabling fixing at the end of the section


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 …


  • 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) {
  } else if (windowTop > sectionStarts) {
  } else {

$(window).scroll(function() {
div:not(.menu) {
  height: 300px;
.menu {
  background-color: lightgray;
.menu.fixed {
  position: fixed;
  top: 0;
<script src=""></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>
<span id="sectionStarts"></span>
<div>Начало секции</div>
<div>Содержимое секции</div>
<span id="sectionEnds"></span>
<div>конец секции</div>
<div>Конец страницы</div>
Scroll to Top