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

Converting Data from MySQL and PHP to Excel

Is there a way to export human resource applications stored in my MySQL table as an Excel file? function exportExcel($filename='ExportExcel',$columns=array(),$data=array(),$replaceDotCol=array()){ global $connect; header('Content-Enc ...

The mark-compacts were not efficient enough, they approached the heap limit and as a result, the allocation failed. The JavaScript

Currently working with Angular version 7.2 and encountering an issue when running ng serve: FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory What does this error mean? How can it be resolved? The ...

Dealing with Unreliable Data in Scatter Plots using React and HighCharts

Initially, I utilized line charts for my data visualization needs. However, I now require multiple data points on the same X-Axis with tooltips, which has led me to discover HighCharts behavior: "In a line chart, by default, Highcharts will display t ...

AngularJS's ScrollTo function allows users to scroll to a specific

Trying to implement a quick nav that smoothly scrolls to different sections on the page when a link is clicked. Currently using a guide provided by Treehouse for reference. $("#quickNav a").click(function(){ var quickNavId = $(this).attr("href"); ...

A guide on how to assign a placeholder as the default value for a date picker

Currently using Vue3 with options API, and this question does not pertain to date formatting. Looking at the code provided on StackBlitz here, the default format for the date being initially set is dd.mm.yyyy. I am interested in knowing how to set the date ...

Learn how to easily alter the background color of a div in real-time by utilizing a color picker or color swatches feature in your

Would it be feasible to dynamically alter the background color of the .hasPicked class? I am interested in adjusting the background color using an input color picker and color swatches. I have already included the necessary code on Codepen. Check it out h ...

Enhancing safety by utilizing varying programming languages

Is there a way to verify the login status using various programming languages? Currently, I am utilizing three sessions with the same name that begin simultaneously after the login process, incorporating ajax. At present, the processing of the login.html ...

Sending multiple objects using Ajax and fetching them in PHP

I'm facing an issue with posting a form and an array to my PHP script. My current approach involves using the following code: var json_data = JSON.stringify(data_vendor); //array to be posted $.ajax({ url: &ap ...

Creating code to ensure a div element is displayed only after a specific duration has elapsed

Can anyone help me with coding to make a div appear on a website after a specific amount of time? Here's an example of what I'm trying to achieve: <div class="container"> <div class="secretpopout"> This is the hidden div that should ...

How can I avoid C3.js legends from overlapping when hiding or showing a div?

Every time I visit a specific page, a simple chart is automatically generated: function displayOptions() { $("#div1").show(); chartRef.flush(); } function displayChoices() { $("#div1").show(); } $("#div1").hid ...

Submitting HTML elements from a webpage using PHP

Is there a way to store an entire HTML table as a single record in my database? I would like the following table data to be submitted when I click the submit button: <table> <tr><td>Items</td></tr> </table> Can thi ...

The functionality of Jquery-chosen appears to be malfunctioning when applied to a select element

I am encountering an unusual issue with Jquery-Chosen. There is a multi-select box within a pop-up where the options are populated using an ajax call. Strangely, Jquery-Chosen does not seem to work on it. However, if I use a static multi-select box in the ...

How to Dynamically Update Sass Styles with Webpack 2?

Currently, I am in the process of setting up a React application that utilizes Webpack2, webpack-dev-middleware, and HMR for the development phase. One peculiar issue that I have encountered is related to updating .scss files. When I make changes to my .sc ...

What is the difference in performance between using named functions versus anonymous functions in Node.js?

Currently, I am working on a Node.js app and was initially using anonymous functions for callbacks. However, after referring to the website callbackhell.com, I discovered that using named functions is considered best practice for coding. Despite switching ...

Transferring information from a form with multiple fieldsets to php

I am facing an issue with my form that is built using multiple fieldsets. The problem is related to passing values from each fieldset to welcome.php upon submitting the form. However, when I click submit, nothing happens and the values are not displayed. A ...

Looking to create a centered 'ul' using Bootstrap

I am looking to center the list with a specific width. body { background-color: rgb(26, 40, 114); } h1 { color: white; text-shadow: 7px 7px 10px black; } li { list-style: none; border-radius: 5px; border: 2px solid white; background-colo ...

Holding off on completing a task until the outcomes of two parallel API requests are received

Upon page load, I have two asynchronous API calls that need to be completed before I can calculate the percentage change of their returned values. To ensure both APIs have been called successfully and the total variables are populated, I am currently using ...

Issue with socket malfunctioning when integrated with express

I’m encountering an issue with the socket in my program. While I can easily broadcast from any part of the program using "io" connection, I face limitations when trying to use "socket" for broadcasting unless it is within the same connection as "io." I a ...

Resizing an image within an anchor tag

Currently, I am working on styling a page in NextJS. The challenge I'm facing is resizing an image that is inside an anchor within a div. Despite numerous attempts, the image refuses to resize as desired. I've experimented with applying properti ...

Having trouble retrieving the data from the angular app factory

I'm attempting to pass a variable between controllers using Angular's Factory. Here is the code snippet I have for this: var app = angular.module('chartApp', ['ngRoute']); app.factory('UserVerified', function() { ...