Modify the hash URL in the browser address bar while implementing smooth scrolling and include the active class

I have implemented a smooth scroll technique found here: https://css-tricks.com/snippets/jquery/smooth-scrolling/#comment-197181

    $(function() {
        $('a[href*=#]:not([href=#])').click(function() {
            if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
                || location.hostname == this.hostname) {
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
                   if (target.length) {
                     $('html,body').animate({
                         scrollTop: target.offset().top -104
                    }, 1000);
                    return false;
                }
            }
        });
    });

The technique works well for one-page site navigation, however, the browser's address bar does not update with the correct hash URL. For example, when navigating from domain.com to domain.com#foo, although it goes to the section id foo, the address bar still shows domain.com as the URL without #foo at the end.

Is there a way to automatically update the URL with the hash as the user navigates through the page?

In addition, I would like to implement adding an active class to the navigation bar to highlight the section that the user is currently on. This means that when they click a link to #foo, the class "active" should be automatically added. As they scroll away to another section, it should then be removed.

Any assistance with this would be greatly appreciated. Modifying existing JQuery code is not my area of expertise, so any guidance would be helpful.

Thank you!

Answer №1

Do you have experience using waypoints in your projects?

let waypointElement = new Waypoint({
    element: document.querySelector('#waypoint'),
    handler: function(direction) {
        console.log('Reached the designated waypoint!')
    }
});

Check out this link for more information on waypoints!

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

Issue with jquery .click function not triggering after CSS adjustment

In the process of creating a fun game where two players take turns drawing on a grid by clicking <td> elements. Currently, I have implemented the functionality to toggle the background color of a <td> element from black to white and vice versa ...

Maintain visibility of the vertical scroll bar while scrolling horizontally

Currently, I am in the process of setting up a table with fixed headers and columns that have a minimum width. To ensure this setup functions correctly, I require both vertical and horizontal scroll bars. The vertical scroll bar should only navigate throu ...

What is the reason behind the absence of unwrapping when utilizing a ref as an element within a reactive array or reactive Map?

The Vue documentation states the following: Unlike reactive objects, there is no unwrapping performed when the ref is accessed as an element of a reactive array or a native collection type like Map Here are some examples provided in the documentation: c ...

What is the best way to implement this component into my vue.js project?

I am having trouble integrating this vue component into my app as it is not loading properly. You can find the source of the component here. The following warnings are showing up: Unresolved function or method isNumeric() at line 35 Unused parameter e at ...

Is the parameter retrieval method correct or erroneous?

I am looking to retrieve data by clicking a link. Here are the links available: <a class="note" id="' . $data["p_id"] . '" value="1" href="javascript:void(0)">+1</a> <a class="note" id="' . $data["p_id"] . '" value="-1" ...

Harnessing the power of Selenium to locate an anchor tag containing HTML elements with specific classes

I have a specific element on my webpage that I need to extract the text "Add New Member" using Selenium. Here is the HTML code for the element: <a ng-if="userCanEdit" class="btn btn-primary ng-scope" ui-sref="orgs-add" href="#/orgs/add"> <i& ...

Exploring the possibilities of combining Selenium Code and F# with Canopy

Currently, I am facing the challenge of incorporating Selenium code into my F# project while utilizing the canopy wrapper. Canopy relies on Selenium for certain functions. My main struggle lies in converting Selenium code from Java or C# to fit within an ...

Ways to verify if a string is a number without using isNaN and with specified criteria

I am trying to determine if a string represents a valid number without relying on the isNaN function. The reason for this is that I need to be able to accept the ',' character, which isNaN ignores. Additionally, I do not want to allow negative nu ...

Vue.js application failing to display images fetched from the server

When I'm running my Vue.js app locally, the images are loading fine from the "src/assets" folder. However, when I deploy the app to Firebase, the images are not displaying and I get a 404 error. What could be causing this issue? I have tried using: ...

Modify radio button colors upon selection with a variety of colors

Looking to create Yes/No buttons that start with a default state of null and change color when pressed - green for yes, red for no. Check out this example code: <label class="formheading">Apparatus group is correct</label> <fieldset data-r ...

When the email field is changed, the string is not being set to the state if it is

I encountered a strange issue while setting an email input as a string to state. Even though I can see on React Dev Tools that it gets sent, when I try to log it from another function, I get an empty string. The odd part is, if I change the order of the in ...

Ways to recycle a section of Javascript for multiple uses on a single page

As a newcomer to website building, I have a query regarding the usage of a JavaScript function designed for a slideshow. My one-page website comprises multiple slideshow units with their own divs, holders, and counters (e.g., 1/4). A JavaScript code contro ...

Searching for the right style before utilizing jQuery to add an element in just one go

My goal is to customize a popup generated by a plugin, but I have limited access to the HTML file for direct editing. So, I am experimenting with using jQuery to achieve this. Essentially, when the styling of the PopUp changes to become visible, I want to ...

The installation of @grpc/grpc-js does not include all necessary dependencies

Recently, I incorporated @grpc/grpc-js into my project using the command npm i @grpc/grpc-js. Surprisingly, there are no compile time errors when I attempt to use it. However, at runtime, a series of errors arise: ./node_modules/.pnpm/@<a href="/cdn-cgi ...

What is the best way to implement a day timer feature using JavaScript?

I am looking for a timer that can automatically change the rows in an HTML table every day. For example, if it is Day 11, 12, or 25 and the month is February at 8 AM, the rows should display "Hello!". function time() { var xdate = new Date(); var ...

Once a value is selected from the datalist input autocomplete, it loses focus

My issue involves using an input with a dynamic datalist for auto completion. To achieve this, I've implemented the following approach: A key function in my process is as follows: $(function () { $("#to").on("input", function (e) { ...

When using Jquery, hovering over an element will cause the full title to be

I have created a toggle div that displays an ellipsis (...) when the long title is longer than 30 characters. Now, I want the full text of the long title to appear when hovering over the div. Check out this JS Fiddle for reference. JS $('#popu ...

Challenges with fading images using jQuery

I am currently working on animating a 5 image slideshow by creating a fading effect between the images rather than just switching abruptly. Here is my HTML structure: <div id="slides"> <ul class="pics"> <li><img src="imag ...

What is the best way to incorporate a custom string into an Angular application URL without disrupting its regular operation?

In my Angular application with angular ui-router, I am facing an issue with the URL structure. When I access the application from the server, the URL looks like localhost/..../index.html. Once I click on a state, the URL changes to localhost/.../index.htm ...

Disable the smooth scroll animation when transitioning between pages using the Link component in NextJS

Not sure if this is a new feature of Next.js, as I didn't encounter this issue in my previous Next.js project. When I reach the bottom of a page and try to navigate to another page, a scroll-to-top animation appears on the destination page. I want to ...