0

i'm trying to make a function that toggles a current class for each navbar item when its corresponding section is scrolled into view. anyone got any idea what i'm doing wrong?

$(function () {

  $(document).scroll(function () {

    var $home = $(".home");
    var $about = $(".about");
    var $contact = $(".contact");

    var $home_section = $("#home");
    var $about_section = $("#about");
    var $contact_section = $("#contact");

    $home.toggleClass('current', $(this).scrollTop() > $home_section.top());
    $about.toggleClass('current', $(this).scrollTop() > $about_section.top());
    $contact.toggleClass('current', $(this).scrollTop() > $contact_section.top());

  });

});
mazz
  • 13
  • 3
  • You might want to check this [question](https://stackoverflow.com/questions/40534826/toggleclass-when-specific-section-is-on-screen) – platypurr Aug 30 '21 at 09:05

1 Answers1

1

First, jQuery does not offer a top method on jQuery objects but it offers offset().top (reference).

Second, you need to remove the current class from navigation elements that got scrolled out.

This could be a solution for your problem:

$(function() {
  var $home = $(".home");
  var $about = $(".about");
  var $contact = $(".contact");
  var $home_section = $("#home");
  var $about_section = $("#about");

  var homeOffset = $home_section.offset().top;
  var aboutOffset = $about_section.offset().top;

  toggleActiveNavElement();
  $(document).scroll(toggleActiveNavElement);

  function toggleActiveNavElement() {
    var scrollTop = $(window).scrollTop();
    var currentClass = "current";

    if (scrollTop < homeOffset) {
      $home.addClass(currentClass);
      $about.removeClass(currentClass);
      $contact.removeClass(currentClass);
      return;
    }
    
    if (scrollTop < aboutOffset) {
      $home.removeClass(currentClass);
      $about.addClass(currentClass);
      $contact.removeClass(currentClass);
      return;
    }
    
    $home.removeClass(currentClass);
    $about.removeClass(currentClass);
    $contact.addClass(currentClass);
  }
});
body {
  font-family: sans-serif;
}

#home,
#about,
#contact {
  padding-top: 10rem;
  padding-bottom: 10rem;
  text-align: center;
  color: white;
}

.navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: space-evenly;
  background: beige;
}

.current {
  color: orange !important;
}

#home {
  background: blue;
}

#about {
  background: red;
}

#contact {
  background: green;
}
<div class="navbar">
  <a href="" class="home">Home</a>
  <a href="" class="about">About</a>
  <a href="" class="contact">Contact</a>
</div>

<div id="home">
  Home
</div>

<div id="about">
  About
</div>

<div id="contact">
  Contact
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
isherwood
  • 58,414
  • 16
  • 114
  • 157
Andreas
  • 430
  • 5
  • 21