Emphasizing hyperlinks according to the user's scrolling location

Currently, I am attempting to create a feature where links are highlighted when the user scrolls over the corresponding section on the page. However, there seems to be an issue with the functionality as Link 2 is highlighting instead of Link 1 as intended.

<nav>
  <ul>
    <li><a href="" id="link_1">Link 1</a></li>
    <li><a href="" id="link_2">Link 2</a></li>
    <li><a href="" id="link_3">Link 3</a></li>
  </ul>
   <p></p>
</nav>

<div id="sec_one" class="sections">

</div>

<div id="sec_two" class="sections">

</div>

<div id="sec_three" class="sections">

</div>

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>

*{
  margin: 0;
  padding: 0;
}
nav{
  width: 100%;
  background-color: black;
  position: fixed;
  top: 0;
}

nav ul{
  width: 50%;
  margin: 0 auto;
  list-style-type: none;
  text-align: center;
}

nav ul li{
  display: inline;
  width: 100%;
}

nav ul li a{
  font-size: 40px;
  color: white;
  text-decoration: none;
}

.sections{
  width: 100%;
  height: 2000px;
}

#sec_one{
  background-color: blue;
}

#sec_two{
  background-color: red;
}

#sec_three{
  background-color: yellow;
}

.active{
  background-color: #666666;
}

p{
  color: white;
}

$(window).scroll(function(){
  var scrollPos = $(window).scrollTop();
  var page1Top = $("#sec_one").scrollTop();
  var page1Bot = $("#sec_one").outerHeight();

  var page2Top = $("#sec_two").scrollTop();
  var page2Bot = $("#sec_two").outerHeight();

  var page3Top = $("#sec_three").scrollTop();
  var page3Bot = $("#sec_three").outerHeight();

  if(scrollPos >= page1Top && scrollPos < page1Bot){
    $("#link_1").addClass("active");
    $("#link_2").removeClass("active");
    $("#link_3").removeClass("active");
  }else {
    $("#link_1").removeClass("active");
  }

  if(scrollPos >= page2Top && scrollPos < page2Bot){
    $("#link_2").addClass("active");
    $("#link_1").removeClass("active");
    $("#link_3").removeClass("active");
  }else {
    $("#link_2").removeClass("active");
  }

});

Answer №1

You may want to consider using the .offset() method in your code. This way, you'll be able to get the position relative to the document rather than just relative to itself, taking other elements into account.

Additionally, there is no need to check the bottom location. You can simply focus on the top location of the next section.

$(document).ready(function() {
  $(window).scroll(function() {
    var scrollPos = $(window).scrollTop();
    
    var page1Top = $("#sec_one").offset().top;
    var page2Top = $("#sec_two").offset().top;
    var page3Top = $("#sec_three").offset().top;

    if (scrollPos >= page1Top && scrollPos < page2Top) {
      $("#link_1").addClass("active");
      $("#link_2").removeClass("active");
      $("#link_3").removeClass("active");
    } else {
      $("#link_1").removeClass("active");
    }

    if (scrollPos >= page2Top && scrollPos < page3Top) {
      $("#link_2").addClass("active");
      $("#link_1").removeClass("active");
      $("#link_3").removeClass("active");
    } else {
      $("#link_2").removeClass("active");
    }
    
    if (scrollPos >= page3Top) {
      $("#link_3").addClass("active");
      $("#link_1").removeClass("active");
      $("#link_2").removeClass("active");
    } else {
      $("#link_3").removeClass("active");
    }

  });
});
* {
  margin: 0;
  padding: 0;
}

nav {
  width: 100%;
  background-color: black;
  position: fixed;
  top: 0;
}

nav ul {
  width: 50%;
  margin: 0 auto;
  list-style-type: none;
  text-align: center;
}

nav ul li {
  display: inline;
  width: 100%;
}

nav ul li a {
  font-size: 40px;
  color: white;
  text-decoration: none;
}

.nav {


.active {
  background-color: #666666;
}

p {
  color: white;
}
<nav>
  <ul>
    <li><a href="" id="link_1">Link 1</a></li>
    <li><a href="" id="link_2">Link 2</a></li>
    <li><a href="" id="link_3">Link 3</a></li>
  </ul>
  <p></p>
</nav>

<div id="sec_one" class="sections"></div>
<div id="sec_two" class="sections"></div>
<div id="sec_three" class="sections"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №2

To prevent targeting individual elements and using rough IDs, you can assess the scrollTop and offset().top of each element to highlight the necessary item based on the section index:

$(window).scroll(function() {
  var scrollPosition = $(window).scrollTop(),
      navHeight     = $('nav').height();
  $('.sections').each(function(index){
    var offsetTop = $(this).offset().top;
    if((offsetTop-scrollPosition-navHeight) <= 0) {
      $('.active').removeClass('active')
      $('nav a').eq(index).addClass('active')
    }
  })
});
* { margin: 0; padding: 0;} nav { width: 100%; background-color: black; position: fixed; top: 0;} nav ul { width: 50%; margin: 0 auto; list-style-type: none; text-align: center;} nav ul li { display: inline; width: 100%;} nav ul li a { font-size: 40px; color: white; text-decoration: none;} .sections { width: 100%; height: 2000px;} #sec_one { background-color: blue;} #sec_two { background-color: red;} #sec_three { background-color: yellow;} .active { background-color: #666666;} p { color: white;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
  <ul>
    <li><a href="" id="link_1" class="active">Link 1</a></li>
    <li><a href="" id="link_2">Link 2</a></li>
    <li><a href="" id="link_3">Link 3</a></li>
  </ul>
  <p></p>
</nav>
<div id="sec_one" class="sections"></div>
<div id="sec_two" class="sections"></div>
<div id="sec_three" class="sections"></div>

Answer №3

Adjusted the code to streamline your JavaScript by dynamically identifying which div is in view and updating the corresponding nav element class.

var $sections = $('.sections'),
    $lis = $('nav li');

$(window).on('scroll', function(){
  var scrollPos = $(window).scrollTop(),
      navHeight = $('nav').outerHeight();
  $sections.each(function() {
    var top = $(this).offset().top,
        bottom = top + $(this).outerHeight();
    if (scrollPos > top - navHeight && scrollPos < bottom) {
      var $target = $lis.eq($(this).index() - 1);
      $lis.not($target).removeClass('active');
      $target.addClass('active');
    }
  })
});
*{
  margin: 0;
  padding: 0;
}
nav{
  width: 100%;
  background-color: black;
  position: fixed;
  top: 0;
}

nav ul{
  width: 50%;
  margin: 0 auto;
  list-style-type: none;
  text-align: center;
}

nav ul li{
  display: inline-block;
}

nav ul li a{
  font-size: 40px;
  color: white;
  text-decoration: none;
  display: inline-block;
}

.sections{
  height: 200vh; ;
}

#sec_one{
  background-color: blue;
}

#sec_two{
  background-color: red;
}

#sec_three{
  background-color: yellow;
}

.active{
  background-color: #666666;
}

p{
  color: white;
}
<nav>
  <ul>
    <li><a href="" id="link_1">Link 1</a></li>
    <li><a href="" id="link_2">Link 2</a></li>
    <li><a href="" id="link_3">Link 3</a></li>
  </ul>
  <p></p>
</nav>

<div id="sec_one" class="sections">

</div>

<div id="sec_two" class="sections">

</div>

<div id="sec_three" class="sections">

</div>

<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>

Answer №4

It seems like you're looking to create links that navigate to different sections within the same page rather than loading a new page altogether.

An easy way to achieve this is by using ScrollSpy. For detailed instructions, you can refer to the documentation available here.

Below is some example code demonstrating how you can implement this on your webpage:

Start by including the scrollspy.js file in your project. Make sure to adjust the URL based on where the file is located.

<script src="scrollspy.js"></script>

Next, within your script file for the page, you might have something similar to the following:

$('.sections').on('scrollSpy:enter', function() {
  switch($(this).attr('id')) {
    case "sec_one":
      $("#link_1").addClass("active");
      $("#link_2").removeClass("active");
      $("#link_3").removeClass("active");
      break;
    case "sec_two":
      $("#link_1").removeClass("active");
      $("#link_2").addClass("active");
      $("#link_3").removeClass("active");
      break;
    case "sec_three":
      $("#link_1").removeClass("active");
      $("#link_2").removeClass("active");
      $("#link_3").addClass("active");
      break;
  }
}

$('.sections').scrollSpy();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking to create a dynamic Angular reactive form using API response data? Seeking guidance on how to achieve this? Let's

[ { "name": "jkjk", "firstName": "hgh", "lastName": "ehtrh", "replytype": "svdv", "prodCode": "svv", "execu ...

Using AngularJS and D3 to create a custom directive that allows for multiple instances of D3 loading within Angular applications

After creating an angular directive for a d3 forced-directed graph and using the code provided here, I encountered some issues with multiple loads. The directive seemed to load six times each time it was initialized, causing performance problems. To addres ...

Sending a javascript variable to an angularjs scope

Currently, I am utilizing Flask to render an HTML template and wish to transfer the variable add_html_data, which is passed via Flask's render_template, to the scope of an AngularJS controller. I have attempted the following: <body> <di ...

displaying 'undefined' upon completion of iterating through a JSON file using $.each

For my project, I am attempting to extract only the date data from a JSON object. I have successfully looped through the object and displayed it, but the issue arises at the end of the loop where it shows undefined. I am not sure what mistake I am making. ...

Prevent rendering a file in node.js using ejs if it cannot be found

I have a specific folder structure under the views directory, containing an EJS file named profile_60113.ejs views docs profile_60113.ejs To dynamically render the file based on the groupID (where data.groupID == 60113), I use the following c ...

Using Entity Framework to create a one-to-many relationship in ASP.NET MVC 5 with code-first approach, and implementing jQuery autocomplete

I am looking to develop a straightforward website where users can post offers with specific details such as title, description, city, and time. Below is a snippet of my database diagram: https://i.stack.imgur.com/f5kcI.png Users can create multiple off ...

Change the border color of a form field in a material design if the user interacts with the

Is there a way to change the border color of a material form field in Angular when it is touched, focused, or active? I attempted to modify the color by overriding material css-class and also tried creating my own css class, but neither method had any ef ...

Encountering issues when attempting to render a function within the render method in React

When attempting to render the gridWithNode function inside the render method, I encountered an error message stating: "Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant ...

The process of AJAX polling a JSON-returning URL using jQuery's $.ajax() method does not appear to provide up-to-date responses

I am currently working on a project that involves polling a specific URL for a JSON response using AJAX. The initial AJAX request alerts the server of my need for JSON content, prompting it to start building and caching the response. Subsequent AJAX reques ...

Implementing Vue.js functionality to dynamically add or remove values from an array based on the state of a checkbox

I recently embarked on my journey to learn vue.js and I've encountered a challenging issue. I have dynamic data that I render using a 'v-for' loop. Additionally, I have an empty array where I need to store checked checkbox data and remove it ...

Creating Typescript libraries with bidirectional peer dependencies: A complete guide

One of my libraries is responsible for handling requests, while the other takes care of logging. Both libraries need configuration input from the client, and they are always used together. The request library makes calls to the logging library in various ...

Navigating the Angular Controller life cycle

I have set up my application states using ui-router: $stateProvider .state('app', { abstract: true, views: { 'nav@': { templateUrl: 'app/navbar.html', controller: 'NavbarController' ...

The Ajax textbox is not providing any automatic suggestions in response to the typed

Having trouble setting up an auto-suggestion AJAX box as there seems to be no response from the server. <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <head> &l ...

Why is there an excessive amount of white space on my Reactjs page?

This webpage (page URL -) displays well without any white space between two images when viewed on a laptop. However, when accessed on a mobile device, it appears to be taking up too much space as shown in the image below. Image of webpage on laptop- lapto ...

When the Ajax "GET" request is made to the intra-service, the CMS service worker will respond with an "OK" even when offline

Hello there, We are currently utilizing an open-source CMS that recently received an upgrade with a new feature - a javascript serviceworker implementation to manage all requests. This CMS includes workflow forms where users engage (created by us). Durin ...

An error occurs when calling useSWR in a function that is neither a React function component nor a custom React Hook function

When using useSWR to fetch data from an endpoint, I encountered the following error (I only want to fetch data onclick) "useSWR is called in function `fetchUsers` that is neither a React function component nor a custom React Hook function" Error ...

When switching windows or tabs, the user interface of the browser extension vanishes

As someone who is new to web application development and browser extension creation, I have encountered a challenge with my browser extension. When the extension popup is open and I switch browser windows, the UI (popup.html) disappears. It reappears whe ...

What is the best way to add both the id and the full object to an array list at the

Requirements: "admin-on-rest": "^1.3.3", "base64-js": "^1.2.1", "react": "^16.2.0", "react-dom": "^16.2.0" I have a User model that includes a List of Roles. // User { id: "abcd1234", name: "John Doe", ... authorities: [ { ...

Grabbing specific inline JSON data with jQuery's .getJSON function or a comparable method

I am trying to extract information from an array embedded within a <script> tag using jQuery's .getJSON method. According to the documentation I've come across (http://api.jquery.com/jquery.getjson/), .getJSON typically needs a URL and an e ...

Filtering data from an array in PHP

I have a code snippet that functions well when the target variable is a single value. The assumption here is that $bank_country represents a single value, such as Brazil, with no issues. <select class="form-control" multiple="1" name="country[]"> & ...