Navigation that sticks and changes upon hovering over div elements

Just delving into the world of jQuery and JS, so I appreciate your patience:)

Currently, I have a sticky navigation bar positioned at the top of my webpage that links to different sections of content below. I am looking to create an effect where the corresponding section is automatically highlighted as the user scrolls through it (even if they scroll manually instead of clicking the link).

For a visual reference, you can see what I mean by visiting this website (*pay attention to how the navigation bar changes when scrolling over each associated page): .

While I've successfully implemented the jQuery sticky plugin for the sticky menu functionality, I am struggling to figure out how to add the hover effect.

Answer №1

This tutorial provides clear instructions on implementing a sticky navigation header with jQUery Waypoints.

Answer №2

Essentially, the issue can be broken down into two main components:

1. Identifying the Location of Each Section on the Page

In order to emphasize a navigation element for each section, it's crucial to first determine the exact location of each section.

I recommend using a class such as .section to define your sections and assigning a name attribute to differentiate between them. Your markup should resemble something like this:

<html>
  <head>...etc.</head>
  <body>

    <ul>
      <li class="nav" id="nav_one">1</li>
      <li class="nav" id="nav_two">2</li>
    </ul>

    <div class="section" name="one"> Section one</div>

    <div class="section" name="two"> Section two</div>

  </body>
</html>

Use JavaScript to locate the position of each section:

//define a sections object
var sections = {}

//find all sections on the page, then for each:
$('.section').each(function(){
  //add a property to the object with a key corresponding to the name
  //and a value corresponding to the offset from the top of the page.
  sections[$(this).attr('name')] = $(this).offset().top;
});

2. Determining the User's Position on the Page

The second aspect involves identifying which sections are currently in view. This dynamic changes as the user scrolls, necessitating the use of jQuery's scroll() event handler:

//the function passed as an argument will be called every time the user scrolls.
$(document).scroll(function(){
  //get the new position
  var newPos = $(this).scrollTop();

  //configurable variable to decide how close a new section needs to be to the
  //top of the page before it's considered the active one.
  var OFFSET = 100;

  //analyze all sections and determine the active one based on proximity to the top
  for(name in sections){
    if(sections[name] > newPos && sections[name] < newPos + OFFSET){
      //the section with name = name is within OFFSET of the top

      //remove "active" styling from the previously active nav elements
      $('.nav').removeClass('active');

      //set the nav element with an id of nav_sectionname as active
      $('#nav_' + name).addClass('active'); 
    }
  }
});

Check out this Codepen example for reference

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

Issues with invoking C# event through ajax communication

Whenever I click the Button, an Ajax method is called that triggers a webmethod on the server side. However, currently, the [WebMethod] is not being executed as expected. Below are the snippets of both the Ajax and server-side code: Ajax code $(document ...

"What is the process for developing a Web-component with Vue and typescript that can be used in

Utilizing vue-custom-element, I have successfully created a Web component in Vue and integrated it into Angular. This setup operates seamlessly for Vue+js: import Vue from 'vue' import Calculator from './components/Calculator.vue' impo ...

Add a span tag with the class "javascript" around the index of a character within a string

Within an element, I have a string as such: <p>I like trains and planes</p> Using jQuery's .text(), I extract the text and store it in a variable. var str = $('p').text(); I aim to identify a specific character, let's sa ...

I'm having trouble pinpointing the issue in my code

For some reason, the first button in the div in this code is not working on HTML files. I have tried multiple JavaScript and HTML validators but none of them seem to work. Surprisingly, it works fine on codecademy.com and w3schools.com, but the issue persi ...

Having trouble invoking html2canvas within an AngularJS app

When I define html2canvas functions in my controller, the alert in html2canvas doesn't get fired and my canvasToImageSuccess function is not executed. Am I missing something here? In my controller, I have defined html2canvas functions as shown below ...

The value produced by the interval in Angular is not being displayed in the browser using double curly braces

I am attempting to display the changing value on the web page every second, but for some reason {{}} is not functioning correctly. However, when I use console.log, it does show the changing value. Here is an excerpt from my .ts code: randomValue: number; ...

"Attempting to dynamically include Components for SSR bundle in React can result in the error message 'Functions are invalid as a React child'. Be cautious of this

When working with my express route, I encountered an issue trying to pass a component for use in a render function that handles Server-Side Rendering (SSR). Express Route: import SettingsConnected from '../../../client/components/settings/settings-c ...

How to prevent multiple JQuery mouseenter events from firing when divs are overlapping

Currently, I am using the JQuery mouseenter event to display a smaller DIV B inside another DIV A. However, I am facing an issue where when I hover over DIV B, the mouseenter event gets triggered again. What I actually want is for DIV B to be shown and hav ...

Tips for resolving the issue of "Unable to assign property '_DT_CellIndex' to undefined in Jquery Datatable"

<?php if(mysqli_num_rows($result)>0) {?> <table class="table table-striped" id="example" align="center"> <tr> <thead> <th style=&quo ...

What is the best way to design lists that adjust to different screen sizes by incorporating multiple columns within the available width?

Back in my old fixed-width days, I had a clever method of distributing data across three columns by dividing the number of elements by three. It worked pretty efficiently. Now in this modern responsive world, my current solution involves splitting data in ...

Unable to invoke the jQuery datetimepicker function within a personalized directive

I have created a unique time picker directive in AngularJS to display a datetimepicker. app.directive("timePicker", function() { return { restrict: "A", link: function(scope, elem, attrs) { / ...

Why is req.user returning as undefined when using Express and Passport?

After setting up my app to redirect to "/", I encountered an issue where req.user is undefined. However, in the twitter callback, req.user provides me with the necessary data. It seems that I lose the data on the redirection. Even though there is ...

Processing MongoDB elements in NodeJS by retrieving them and appending them to a list or array for further processing

Currently, I am involved in a full stack project that requires fetching stock data from mongodb and performing algorithms on specific information. Here is an illustration of the JSON object stored in mongodb: [{ _id: 5e11d67abf05f3d00d56b801, LUNA: { ...

Discovering the actual file path of an uploaded document in Asp.Net Mvc

When trying to use an HTML input file to select a file, I encountered an issue where JQUERY would return a fake path instead of the actual one. $("#inputfile").val() I am looking to obtain the selected file's actual path, such as: D:\Documen ...

What is the best way to ensure an image is responsive in CSS and aligns perfectly in height with its neighboring text?

There is an image within the <img> tag and some text inside the <p> tag, both enclosed in a <div>. Although the image is responsive and resizes proportionally when the browser window changes size, there is an issue where as the text wrap ...

How to use the v-model to round up a number in Vue.js

I need to round up a number in my input field: <b-form-input id="amount_input" type="number" v-model="Math.ceil(form.contract.reward_cents / 100)" :state="validate(form.contract.reward_cents)"/> ...

Utilizing Sessions Across Several PHP Forms

Hey there! I've got a query for you. When you kick off your PHP code with session_start(), do you need to keep adding the prior variables on subsequent form pages? I'm contemplating using the session() function for my GYM Sign UP Webpage. The f ...

Customize the element of the root node of a MUI component using the styled()

I am trying to implement the "component" prop with a MUI component (such as ListItem) using the styled() API. However, I am facing an issue where it says that "component" is not a valid prop. Can someone guide me on how to correctly achieve this? I have se ...

Why does Typescript not enforce a specific return type for my function?

In my custom Factory function, I need to return a specific type: type Factory<T> = () => T; interface Widget { creationTime: number; } const createWidget: Factory<Widget> = () => { return { creationTime: Date.now(), foo: &a ...

Unraveling the Perfect Jest Stack Trace

Currently, I am in the process of debugging some tests that were written with jest using typescript and it's causing quite a headache. Whenever a test or tested class runs Postgres SQL and encounters an error in the query, the stack trace provided is ...