Using an ID and name, the anchor tag dynamically updates as you scroll

Having trouble figuring out how to make this work, despite numerous examples that don't quite fit my situation or code. I'm deeply invested in this project and can't afford to start over from scratch. I've made significant progress but can't seem to get the anchor tag in the menu to change as the user scrolls on the page.

Is there a simple solution using the latest jQuery and JavaScript that will work with my existing code?

Or am I doomed to restart the entire project?

Here is a snippet of the code I currently have:

<nav id="menu" class="menu">
                <a class="menu-trigger"></a>
                <ul>
                <li><a href="#">:: Join Community ::</a></li>
                <li><a href="#home_wrapper" class="active">Home</a></li>
                <li><a href="#about_wrapper">About</a></li>
                <li><a href="#advertise_wrapper">Advertise</a></li>
                <li><a href="#central_wrapper">GP Central</a></li>
                <li><a href="#contact_wrapper">Contact</a></li>
                <li><a href="#career_wrapper">Career</a></li>
                <li><a href="#press_wrapper">Press</a></li>
                <li><a href="#">:: My Dashboard ::</a></li>
            </ul>
            </nav>


<div id="main_body">

            <div id="about_wrapper">
            </div>

            <div class="clear"></div>

            <div id="advertise_wrapper">
            </div>

            <div class="clear"></div>

            <div id="central_wrapper">
            </div>

            <div class="clear"></div>

            <div id="contact_wrapper">
            </div>

            <div class="clear"></div>

            <div id="career_wrapper">
            </div>

            <div class="clear"></div>

            <div id="press_wrapper">
            </div>

        </div>

I've attempted the following script:

$(window).scroll(function() {
var windscroll = $(window).scrollTop();
$('.page').each(function(i) {
    var posTop = $(this).position().top, 
        h = $(this).height();

    if (posTop  <= windscroll && posTop + h > windscroll ) {
        $('.menu ul li').removeClass('active');
        $('.menu ul li').eq(i).addClass('active');
    }
});
});

Any assistance would be highly appreciated!

Answer №1

Thanks to the assistance of 4dgaurav, I was able to locate a solution at last!

let divisions = $('div')
  , navigation = $('.menu')
  , nav_height = navigation.outerHeight();

$(window).on('scroll', function () {
  let current_position = $(this).scrollTop();

  divisions.each(function() {
    let top = $(this).offset().top - nav_height,
        bottom = top + $(this).outerHeight();

    if (current_position >= top && cur_pos <= bottom) {
      navigation.find('a').removeClass('active');
      sections.removeClass('active');

      $(this).addClass('active');
      navigation.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
    }
  });
});

navigation.find('a').on('click', function () {
  let $element = $(this)
    , identifier = $element.attr('href');

  $('html, body').animate({
    scrollTop: $(identifier).offset().top - nav_height
  }, 500);

  return false;
});

Answer №2

Give this a shot,

$(function(){
    $(window).scroll(function () {
        var windscroll = $(window).scrollTop();
        $('ul li a').each(function(i) {
            var posTop = $($(this).attr('href')).position().top, 
                h = $($(this).attr('href')).height();

            if (posTop  <= windscroll && posTop + h > windscroll ) {
                $('.menu ul li a').removeClass('active');
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }
        });
    });
});

Note: Make sure to apply your CSS properly.

Check out the Live Demo here

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

Connecting the input[date] and Moment.js in AngularJS

For the purpose of formulating a question, I have prepared a simplified example: ... <input type="date" ng-model="selectedMoment" /> ... <script> angular.module('dateInputExample', []) .controller('DateController', [& ...

Organize rows in the table while maintaining reactivity

A challenge I'm facing with a web app (Angular SPA) is that it displays a large table without the ability to sort. To work around this issue, I've managed to implement sorting via the console. However, re-inserting the rows after sorting causes t ...

Tips for integrating NPM Modules with Flask

As I deploy my Python application with Flask using the render_template() function onto a webpage, I am also attempting to integrate some JavaScript modules using npm. Even though I have installed the necessary modules in the static folder along with all my ...

divide a single item into several items depending on its attribute

data = {1-inputWidth : '30px' , 1-inputHeight: '30px', 1-color : 'red', 2-inputWidth : '20px' , 2-inputHeight: '10px', 2-color : 'blue', 3-inputWidth : '60px' , 3-inputHe ...

Switch the text within the div and alternate between showing different content in separate divs by utilizing jquery

Check out the jQuery code snippet below: $(document).ready(function () { $('#prvnote').hide(); $('#regclass').click(function () { $('#prvnote').toggle(400); $('#newdiv').toggle(400); }); ...

Is there a way to align the logo in the center vertically with the navigation on the right side of the header?

I've been grappling with this issue. I'm interested in exploring various methods to vertically center elements in navigation using semantic HTML. Specifically, I'd like my logo aligned left and the navigation menu aligned right. I attempted ...

The misbehavior and layout disruptions caused by jQuery code can often be attributed to Ajax calls

If you're looking for my website, it's right here. The code for it is below, and it involves basic DOM manipulations using jQuery. My goal was to add a pop-up feature that fetches its content from an external ".html" file using a jQuery Ajax call ...

Is it possible to use two onChange functions in a single text field with ReactJS?

Is it possible to have two onChange functions in a single Textfield? In my code, "onChange={ showDiv}" is a handler that shows "Direct 2" when clicked and hides upon selecting option1. The second onChange={(e) => exhandleChange(e)} is used for another ...

In the realm of numeric input in JavaScript (using jQuery), it is interesting to note that the keyCode values for '3' and '#' are identical

I am in need of setting up an <input type="text" /> that will only accept numeric characters, backspace, delete, enter, tabs, and arrows. There are many examples out there, and I started with something similar to this: function isNumericKeyCode (ke ...

React-Native Error: Invalid element type detected

While attempting to run my React Native app on my iPhone using Expo, I encountered an error displayed in a red background area. Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite ...

Is there a way to make the background transition colors on scroll for a Tumblr theme

Currently, I am utilizing a Tumblr theme that scrolls horizontally. You can find the theme here. Does anyone have recommendations on how to change the background to red while scrolling and then switch back to white when scrolling stops? This is the CSS c ...

What causes the warning message at runtime from propTypes when auto binding props?

Explanation: I created a basic wrapper to automatically bind the props. Code Snippet: To implement this, start by using create-react-app to set up a new application. Then, replace the contents of App.js with the following code: import React, { Comp ...

Assigning a changing label to a radio button

Looking to create a dynamic form where clicking a button calls a JavaScript function. Here's the code snippet: function addRadioButton(type){ var element = document.createElement("input"); //Set attributes for the element. element.setAttr ...

`Implementing Bootstrap grid system within a PHP loop`

I am currently working on a project that involves extracting data from a database and displaying it on an HTML page using Bootstrap grids. The code snippet below was given to me by someone, and I have made a few modifications by adding two tags: and . How ...

Responsive Text in HTML Email Depending on Device

I currently have an email template that is functioning perfectly, but I am looking to take it to the next level. The top navigation of the email consists of 4 columns of text. To ensure that it appears well on both desktop and mobile devices, the font size ...

How can you execute/ajaxComplete in your code?

Is there a way to initiate a function once an AJAX response is finished? When the dropdown changes, the manageImagesDynamicObjectDetails function is invoked: <select id="imageComponentSelection" name="imageComponentSelection" onchange="manageImagesDyn ...

What is the best way to ensure jQuery loads before CSS code on a website

I am currently working on a blog project that allows visitors to customize the background color by simply clicking on one of five available buttons. $(function(){ //Checking if a color scheme has already been selected var chosenColor = ...

Enclose each number within HTML and Javascript tags

I need help styling the numbers on my random name picker website. Below is the code I'm using: HTML <div class="result-border"> <div class="result overflow-auto"> <div id="text"></div> ...

Converting hexadecimal to binary using Javascript or Typescript before writing a file on an Android or iOS device

Hey everyone! I'm facing a puzzling issue and I can't seem to figure out why it's happening. I need to download a file that is stored in hex format, so I have to first read it as hex, convert it to binary, and then write it onto an Android/ ...

the intricate dance between Node.js and the powerful V8 engine

Understanding the intricate relationship between nodejs and the v8 engine has been a challenge for me. When I write JavaScript code and run it, it is sent to the v8 engine for execution. If my code includes functions provided by nodejs, how does nodejs com ...