Navigate to the top of the page using jQuery

Attempting to implement a simple "scroll jump to target" functionality. I've managed to set it up for all parts except the "scroll to top". The jumping works based on the tag's id, so it navigates well everywhere else, but not to the very top. Here's a simplified version of my code:

<ul class="nav navbar-nav">
    <li class="active"><a id="home" href="#home">Home<span class="sr-only">(current)</span></a></li>
    <li><a href="#services">Services</a></li>
    <li><a href="#about">About Us</a></li>
    <li><a href="#contacts">Contacts</a></li>
</ul>

Further down:

<div id="wall_1" class="myImage" data-stellar-background-ratio="0.4"></div>
    <div id="content_1" class="myContent">
        <div id="services"></div>
        ...
        <p><a href="#Home">Go to the top</a></p>
    </div>
    <div id="wall_2" class="myImage" data-stellar-background-ratio="0.4"></div>
    <div id="content_2" class="myContent" >
        <div id="about"></div>
        ...
        <p><a href="#Home">Go to the top</a></p>
    </div>
    <div id="wall_3" class="myImage" data-stellar-background-ratio="0.4"></div>
    <div id="content_2" class="myContent">
        <div id="contacts"></div>
        ...
        <p><a href="#Home">Go to the top</a></p>
</div>

JS:

<script>
    $(document).ready(function () {
        $('a[href^="#"]').on('click', function (e) {
            e.preventDefault();
            var target = this.hash;
            var $target = $(target);
            $('html, body').stop().animate({
                'scrollTop': $target.offset().top - 81
            }, 800, 'swing', function () {
                window.location.hash = target;
               });
        });
    });
</script>

How can I make it scroll back to the top now?

Answer №1

Try this solution:

$('html, body').stop().animate({
                    'scrollTop': 0
                }, 800, 'swing');

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

What is the best way to make a Dojo TitlePane overlap using CSS?

My dilemma involves a jsfiddle featuring two TitlePane widgets in the central pane's top right corner. Currently, clicking on the right TitlePane ("Switch Basemap") moves the left TitlePane ("Map Overlays") to the left. What I want is for the right Ti ...

Send the cookie with the JSON request

While logged into a secure website with a login, I came across some valuable data that is transmitted through the server in JSON format. By opening Chrome and inspecting the page using the "Network" tab, I discovered a URL utilizing XHR which contained the ...

Storing multiple email addresses in an array using an HTML input element

I have a small React Bootstrap form where I am trying to save multiple email addresses entered by the user into an array. However, when I use onChange={()=> setEmails(e.target.value as any} it stores them in string format like this --> [email p ...

Reply in Loopback on remote method beforeRemote hook is to be sent

In my application, I am utilizing loopback v3. The specific use case I am tackling involves validating the presence of a token in the request header. If the token is invalid, I need to send an appropriate message in a standardized format. My approach has b ...

Encountering an "undefined" error when implementing the useReducer hook in React

I'm encountering an error when using the UseReducer hook in React. Even though I have destructured the state object, I still receive this error: const [{previousOperand,currentOperand,operation},dispatch] = useReducer(reducer,{}); return ( ...

Find the total number of records in fnClick: (datatables.net)

I am struggling with some code where I need to retrieve the total number of records. I posted about it on the datatables.net forum but unfortunately, no one was able to help me... tableTools: { "sSwfPath": window.STATIC_BASE + "scripts/datatable/s ...

What is the reason that my "width: auto" property is not properly adjusting to the content's width?

My css code, width: auto is causing issues with the content width I am a beginner in HTML, CSS, and JavaScript, seeking help with my website. I have multiple divs within a section element, but the section's width is not adjusting to fit the divs prop ...

Output the Partial View as a string within a Bootstrap Modal

Is there anyone who can help me? I am facing an issue with my View and Partial View (to be loaded in a Bootstrap modal). When I try to convert my partial view to a string, so it can be returned to my view, it comes back empty. However, if I add some tags ...

Techniques for transferring JavaScript variables within a URL using AJAX

Is there a correct way to pass the values of accesstoken and pageid inside the URL I am using? Any ideas on how to do it properly? <script type="text/javascript"> function makeUrl() { var accesstoken = "12345679|bababashahahhahauauuaua"; ...

Chrome browser experiencing a disappearing vertical scroll bar issue on a Bootstrap Tab

<div class="tabs-wrap left relative nomargin" id="tabs"> <ul class="nav ultab" id="fram"> <li class="active"><a href="#history" data-toggle="tab" id="history1" >History< ...

Determine the prior location of an element using jQuery

Is there a way to track the previous location of an element before it is appended? I have 50 elements that need to be appended to different targets based on a certain condition. How can I determine where each element was located before being moved? $(&a ...

Tips for styling a PHP file using CSS and styling more than one element:1. Begin by creating a

I am currently attempting to style a php file using a linked stylesheet, but I am encountering some difficulties. At the moment, I have the , it will affect either the font or the border.</p> Is there a way to apply multiple styles to elements on a ...

What impact does reducing the window size have on my header?

While working on a website with a navigation bar, I encountered an issue where the navbar was not responsive. When the window size was reduced, the nav bar shifted to an awkward position vertically, as shown in the first image. The navbar shifts below the ...

The Node.js POST request is unexpectedly returning 'undefined'

I'm currently working on a project for an online course and I'm encountering an issue with making an API call. It seems that I am getting undefined responses to my post request because the user input is not being retrieved properly. Below are the ...

Creating a stylish CSS shadow effect for a collection of elements

In my Ionic2 project, I have an <ion-list> consisting of various items. Currently, these items are plain, but I desire to add some styling such that each item in the list displays a subtle shadow effect, similar to the one shown in the first image of ...

Acquire by Identifier - Tonic()

Currently, I am in the process of setting up a code example on tonicdev.com for my open-source React component available on Npm. Below is the code snippet that I am attempting to execute (editable live on tonicdev.com here): var React = require('rea ...

Searching for text in an HTML table using PHP DOM query

How do I extract text from HTML table cells using PHP DOM query? Here is a sample HTML table: <table> <tr> <th>Job Location:</th> <td><a href="/#">Kabul</a> </td> </tr> <tr> ...

AngularJS and Gulp: Enhancing Static Assets with Revisioning

I have implemented the gulp-rev module to re-vision static assets in my source files. It generates new file names for CSS, JS, and HTML files by appending a hash code to it. Before : app.js After : app-2cba45c.js The issue I am facing is that in my An ...

What is the best method for retrieving data from a specific collection in MongoDB?

Within the code snippet below, on the 4th line, 'Messages' is the name of my MongoDB collection that I created in another file. When I attempt to retrieve data from this collection, no errors occur. However, when I specify the name of a differen ...

Is there a way to customize the CSS of a Bootstrap 4 data table

I recently incorporated a library from Bootstrap Datatables into my project. However, I'm having trouble modifying the CSS for the search bar and 'Excel' button. Is there a way for me to customize it with my own CSS? https://i.sstatic.net/x ...