Adjust the current jQuery code to update the URL as the user scrolls

I have a jQuery code from w3schools.com that changes the URL's #id and enables smooth scrolling to a specific DIV section when clicking an <a href="#id"></a>. However, it does not work on scroll. I am looking for a solution where the URL's #id changes as I scroll up or down to a particular section.

Here is the current jQuery Code:

$(document).ready(function(){
  $("#navlist a").on('click', function(event) {
    if(this.hash !== ""){
      var hash = this.hash;
        $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){
        window.location.hash = hash;                
      });
    }
  });
});

I found something on stackoverflow that seems to address the scrolling issue:

$(document).bind('scroll',function(e){
    $('div').each(function(){
        if ($(this).offset().top < window.pageYOffset + 10 && $(this).offset().top + $(this).height() > window.pageYOffset + 10){
            window.location.hash = $(this).attr('id');
        }
    });
});

While this seems to work independently, combining both codes causes one of them to stop functioning. I would like to merge them to achieve both onclick and scroll effects, but my knowledge of jquery is limited.

For example, a URL with ID:

http://localhost/sites/fh/index.php#first

Any help provided will be greatly appreciated. Thank you!

Answer №1

To prevent forced page scrolling by the browser, it is recommended to change the history state instead of setting the location hash. Here is an example of how you can achieve this:

navlist = [];
$("#navlist a").each(function(i) {
    var thisLink = $(this);
    var thisId = thisLink.attr('href');
    var thisTarget = $(thisId);
    navlist.push({
        'anchor': thisLink,
        'id': thisId,
        'target': thisTarget
    });
    thisLink.on('click', function(e) {
        e.preventDefault();
        $('html, body').animate({
            scrollTop: thisTarget.offset().top
        }, 800);
    });
});
$(window).on('scroll resize', function(e) {
    $.each(navlist, function(e, elem) {
        var placement = elem.target[0].getBoundingClientRect();
        if( placement.top<window.innerHeight && placement.bottom>0 ) {
            history.pushState({}, '', elem.id);
            console.log('Hash: ' + elem.id);
            return false; /* Exit $.each loop */
        };
    });
});
nav a {
    display: block;
}
section {
    height: 600px;
    border-top: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="navlist">
    <a href="#s1">Go to Section 1</a>
    <a href="#s2">Go to Section 2</a>
    <a href="#s3">Go to Section 3</a>
</nav>
<section id="s1">Section 1 Content</section>
<section id="s2">Section 2 Content</section>
<section id="s3">Section 3 Content</section>

Visit this JSFiddle link for a live demo.

Note that Foundation framework users already have Magellan and Bootstrap users have ScrollSpy for similar functionality.

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

Learn the process of invoking componentDidMount each time you switch between ListItems in React

After initializing the widget component to load various charts, it works correctly. However, when switching to another ListItem, the componentDidMount does not load the required data. This data is essential for the component to function properly. I noticed ...

Creating a standalone executable for Node.js without including the entire Node.js framework

Trying to pack a simple hello world script into an executable has led to some challenges. Both pkg and nexe seem to include the entirety of Node.js in the output file, resulting in quite larger files than necessary (around 30 MB). Although EncloseJS was fo ...

AngularJS: How to accurately retrieve the offsetTop value upon page initialization

Issue: I am facing difficulty in obtaining the accurate top offset value of a DOM element immediately after the page has loaded. In the project I am currently working on, it is essential to retrieve the offsetTop value of various DOM elements as soon as ...

Sending data between Node.js middleware components

if (token_count == 1) { var user_name = rows[0].user_name; next(); } else { data = { message: "Invalid Token" } res.send(data); } I must pass the parameter user_name to function next(). When next() is called, it triggers the fo ...

Learn how to create a visually stunning CSS menu by centering a background image from the website cssmenumaker

I found a ready-made dropdown menu on . The menu is working well, but I would like to center the buttons. Is there a way to do this? Here is the CSS code: @import url(http://fonts.googleapis.com/css?family=Open+Sans:600); /* Menu CSS */#cssmenu, #cssmenu ...

Implementing reCAPTCHA and PHP for Email Form Submission

Currently using GoDaddy as the web host for my website. Struggling to integrate reCAPTCHA into the email form on my site. I successfully pass the reCAPTCHA test, but emails are not being sent. So far, the website has been built using PHP and HTML only. ...

What is the best way to distinguish between an IPFS URL or path (content-addressed) and a regular URL (location-addressed)?

I need to retrieve nft-metadata for the nfts that have been added to my platform. Some of these Nfts have ipfs-urls as their tokenURIs and I am looking for a way to distinguish them from regular urls (location-addressed urls). Previously, I used is-ipfs, ...

What happens to the XMLHttpRequest when the browser is closed?

If I begin an XMLHttpRequest when the onClose event of the tab or browser window is triggered, what should I anticipate? Will the request be terminated if it takes too long or will it be allowed to complete even as the window closes, possibly resulting in ...

Passing arguments from an Angular directive to a controller function within an element's HTML

Is there a way to pass the URL of an anchor tag in the directive to the controller function "itemClicked"? The code below successfully logs the "post" object when clicked. HTML: <div ng-repeat="post in posts" > <div find-urls link-clicked="i ...

Utilizing FormHelper in CakePHP to send search query to controller parameter

How can I pass a form directly to a controller parameter in CakePHP 2.4? The controller expects the parameter in the format /Model/index/by:keyword, but FormHelper is adding a question mark and an equals sign into the URL: Model/index?by%3A=keyword. Here ...

How to check Internet upload speed in Angular without using a backend server?

I need help uploading a file to a folder within my Angular app's directory while it is running on localhost. I have been unable to find a solution that doesn't involve using backend technologies. For instance, I simply want to upload an image fi ...

What could be causing my function to fail to return the array?

Here is the code snippet I am working with: document.getElementById('revealUser').onclick = displayDaUsers function displayDaUsers(){ pullAllUsersFromDB(); debugger; } function pullAllUsersFromDB(){ rootRef.child('users').on(& ...

If the font size exceeds a certain value in SCSS, then apply a different value

Can SCSS handle this scenario? I am looking to set the font size to 22px in case it is greater than 30px, especially within a media query for a max width of 480px. ...

Is there a way to eliminate the .html extension from the end of URLs for web pages?

Can someone provide guidance on how to eliminate the .html extensions from file names? Specifically, I noticed this feature on the site tekmillion.com. Your assistance is greatly appreciated. Thank you! ...

Learn how to exchange classes with a hover effect using jQuery

I currently have a 'div' container named 'obj_image' that contains another nested 'div' called 'like_icon'. When a user clicks on the 'like_icon' element, an AJAX request is sent. If the request is successf ...

Is it possible to utilize a slot within a Vue.js loop?

I am encountering an issue with a template that is utilizing v-for to loop through. The template includes a named slot where the name is dynamically assigned within the loop. However, no content is displaying as expected. Can someone help me identify wha ...

Just started working with React and encountered this initial error message in my project

Welcome to Windows PowerShell! Upgrade to the latest version of PowerShell to enjoy new features and enhancements! PS D:\React> cd textutils PS D:\React\textutils> npm start npm WARN config global `--global`, `--local` are deprecated ...

Sending Ajax requests to web services hosted on a dual-node NLB

I am currently managing a two-node NLB configuration where multiple web services need to be accessed from the client-side using ajax POST requests. When visiting the page at: http://clusternode1/ everything works smoothly. Similarly, when accessing it f ...

What is the process for adding tailwind CSS via npm?

Before, I was including Tailwind using a CDN. Now, I have installed it with npm and all three .css files are included, but the styles are not appearing in my HTML document. Here is the directory structure and a link to style.css The content of tailwind.c ...

Angular 6: A guide to dynamically highlighting navbar elements based on scroll position

I am currently building a single page using Angular 6. The page is quite basic, and my goal is to emphasize the navbar based on scrolling. Below is the code snippet I am working with: .sticky { position: sticky; top: 0; } #i ul { list-style-type: ...