Smooth scrolling to an anchor with jQuery

Having recently written a simple smooth scrolling function using the jQuery mousewheel extension, I found myself facing a challenge due to my lack of experience with $.mousewheel.

The gist of my issue is that when the "south delta" is triggered, I invoke an $.animate function that scrolls to a specific class named .anchor.

A simplified version of the HTML code:

<div id="static-section" class="anchor"></div> <!-- width: 100%; height: 258px -->
<div id="alt-section" class="anchor"></div> <!-- width: 100%; height: 346px -->

The associated jQuery code:

$(document).ready(function() {
    $("body").mousewheel(function(event, delta, deltaX, deltaY) {
        if( delta > 0 ) {
            console.log("North: " + delta);
        }

        else if( delta < 0 ) {
            console.log("South: " + delta);
            // ANIMATE TO ANCHOR FUNCTION
            $("html,body").animate({scrollTop: $(".anchor").offset().top}, "slow");
        }

        return false;
    });
});

In summary: My current dilemma involves the animation only targeting the first instance of the .anchor class (which corresponds to

#static-section</code). Despite attempting to use <code>scrollTop: $(".anchor").next().top
, it remains fixed on animating towards the initial instance. I experimented with implementing a for loop as well, but encountered no success. Since I haven't utilized for loops frequently, there's uncertainty regarding whether my approach was correct. Any assistance on this matter would be greatly appreciated!

Note: Unfortunately, jsFiddle (with identical code to my site) doesn't accurately showcase the issue I'm encountering, so a live demo isn't available. If needed, I can provide the URL upon request. :-)

Answer №1

If you want to smoothly scroll through the anchor tags, you can use a script like this:

$(document).ready(function() {
    var $anchor = $('.anchor');
    $("body").mousewheel(function(event, delta, deltaX, deltaY) {
        if( delta > 0 ) {
            console.log("Moving North: " + delta);
        }

        else if( delta < 0 ) {
            console.log("Moving South: " + delta);
            // SCROLL TO ANCHOR FUNCTION
            $("html,body").animate({scrollTop: $anchor.offset().top}, "slow");
            $anchor = $anchor.next('.anchor');
        }

        return false;
    });
});

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

ASP.NET validation expression for allowing digits and certain characters such as "/" and "-"

I am trying to create an expression that will accept / and - characters, like this 123/12-125 (must accept / and -). I attempted to write a ValidationExpression as follows: "^(\d*\/?\d*)^(\d*\-?\d*)$", but it did not work. T ...

Ways to eliminate HTML elements from displayed content

I need help removing the <p> tags from comment text that is rendered. When passing the content to a component as a prop, I am experiencing issues with the v-html directive not working correctly. How can I render the content without the HTML tags? C ...

Changing the key of a JavaScript request object into a string variable

Just starting out with programming. The API post call requires an object variable (derived from a variable) to be passed as a string like this: "option": { "235": “30” }, { "238": “32” } In my Angular 6 code: ...

Tips for adjusting column positions in a table while maintaining a fixed header and utilizing both horizontal and vertical scrolling

Is there a way to display a table that scrolls both horizontally and vertically, with the header moving horizontally but not vertically while the body moves in both directions? I have been able to shift the position of the columns, however, I am struggling ...

Adjusting Div Tag Attributes When Hovering

Can the properties of one div tag be altered when hovering over a different div tag? For instance, #tag1 { /* original properties */ } #tag1 a:hover { /* updated properties */ } #tag2 { /* includes a hyperlink */ } In this scenario, tag1 would under ...

Guide to generating and executing a file in node.js

After installing the newest version of node.js, I verified it in the command prompt by running node-v and npm-v commands. Now, I'm looking to learn how to create and execute files using node.js. Can someone provide guidance on this process? ...

Is it possible to create a collapse and expand animation that does not involve transitioning the `height

After extensively researching, I have come across numerous articles advocating for the use of transform and opacity for achieving smooth CSS transitions. An example can be found here: The prevailing notion always revolves around: ...the optimization ...

How to easily transfer items from TreeView to List Box using Drag and Drop feature in asp

Seeking guidance on coding a drag-and-drop feature from a treeview parent or root node to a list box using asp.net. Any assistance would be greatly appreciated! ...

"Exploring the powerful combination of Django dynamic formsets and the magic

While utilizing django dynamic formset and ajax to check the inventory, I encounter a challenge when trying to make ajax detect changes on newly added forms. How can I achieve this? Dealing with dynamically added forms $('#form-inline tbody tr' ...

The most effective method for monitoring updates to an array of objects in React

Imagine a scenario where an array of objects is stored in state like the example below: interface CheckItem { label: string; checked: boolean; disabled: boolean; } const [checkboxes, setCheckboxes] = useState<CheckItem[] | undefined>(undefined ...

Discovering additional element information while utilizing the 'Sortable' feature

My Current Objective: In my setup, I have a 'calendar' comprising 5 columns, each column containing 5 separate divs known as timeslots. The main purpose here is to show appointments in these specific timeslots and utilize JQuery's Sortable ...

What is the optimal approach for managing script initialization on both desktop and mobile devices?

I have implemented a feature on my website that can detect whether the viewer is using a mobile device. Additionally, I have created a JavaScript script that adjusts settings based on whether the user is on a mobile device or not. However, I am wondering ...

What is the best way to add flair to the HTML <title> tag?

Just a quick question - I'm wondering if there is a method to apply CSS styles to an HTML element. Here's an example declaration: title { color: red; font-family: 'Roboto', sans-serif; } ...

When running the command `npm install <node_module> --save`, the dependencies are not being updated as

<=== If you're facing the same issue, try reinstalling your computer to fix it ===> I recently had to reformat my computer and set everything up again. After reinstalling Node and NPM, I encountered some problems that are really irritating me. ...

Reduce the noise from different versions by utilizing package-lock.json

There may not be a clear-cut answer, but I'm curious to hear how others handle the issue of package-lock.json causing problems when committing to their node repository. Many opinions lean towards committing package-lock.json - ensuring consistent dep ...

Error encountered during the building of a Java project using Gradle

I ran into an issue with Git Bash error output (build failed). Despite attempting to resolve it by installing Python as suggested, setting the Python environment variable in IntelliJ, and following other recommendations, I still encounter the same build ...

Ionic 2's Navigation Feature Failing to Function

I need to implement a "forgot password" feature on my login page. When a user clicks the button, they should be redirected to the "forgot password" page. Below is the code snippet from my login.html <button ion-button block color="blue" (cli ...

Decoding a serialized string into an object

I have a data string that is serialized in the format a=4&b=2&c=7. I am looking to convert this string into an object where each key-value pair is represented like this: { a:4, b:2, c:7 }. When I use serializeArray(), it only gives me an array with ...

Navigate to the most recent entry in the array while using ng-repeat

I am attempting to implement scrolling to the last added entry within an ngRepeat directive. After researching related questions on Stack Overflow, such as #1 and #2, I still cannot find a solution to my problem. The code is straightforward. When a user ...

Tips for implementing a for loop on a JSON file in Node.js

I am facing an issue where I am trying to loop through a JSON array of objects using a for loop. Strangely, it only works when I explicitly pass the index as a number (e.g. parseJSON.sites[0]). When I try to use a variable within the loop, which is preferr ...