The smooth scrolling feature is not functioning properly as the links are jumping to the top and bottom instead of scrolling

My links are supposed to smoothly scroll to the bottom and top, but they're not working correctly even though I believe the JavaScript is functioning properly.

Here is the JavaScript code:

$.fn.ready(function() {

            // Smooth scroll to top.
            $("a[href=#top]").live("click", function(e) {
                $("html,body").animate({scrollTop:0}, 1000);
                e.preventDefault();
            });

            // Smooth scroll to bottom.
            $("a[href=#bot]").live("click", function(e) {
                $("html,body").animate({scrollTop:$(document).height()}, 1000);
                e.preventDefault();
            });
        });

And here is the HTML code for the links:

 <a href="#bot" id="botlink" title="Go to bottom">↓</a>
 <a href="#top" id="toplink" title="Go to top">↑</a>

Answer №1

If you are utilizing the "live" event in jQuery, it seems like you may be working with an outdated version of the library. When it comes to navigating to the top or bottom of a page, it's important to understand the specific positions involved (top = 0, bottom = document.height). A functional jQuery script for this scenario would look something like this:

jQuery(document).ready(function($){

  $('#botlink').add( $('#toplink') ).on( 'click', function( e ){
    e.preventDefault();

    var $btn = $(this).attr( 'id' ).replace('#', '');
    var move_to = $btn === 'botlink' ? $(document).height() : 0;

    $('body').animate({
      scrollTop : move_to
    }, 'slow');

  });

});

The code snippet above detects the click event on either the #botlink or toplink elements. The move_to variable determines which button was clicked and calculates the position of the page accordingly. To achieve the desired effect, it is necessary to animate both the html and body elements.

In reality, the script only affects the body element. Additionally, you can experiment with a live demonstration on jsFiddle here (the body element has been expanded to 1200px to showcase the effect).

Answer №2

take a look at this fiddle, it could be useful for you

Check out the Js Fiddle

$("a[href=#top]").on("click", function (e) {
    //alert("top")
    $('html, body').animate({
        'scrollTop': 0
    }, 1000)
    event.preventDefault();
});

// Smooth scroll to bottom.
$("a[href=#bot]").on("click", function (e) {
    // alert("bottom")
    var a = $(document).height()
    $('html, body').animate({
        'scrollTop': a + 'px'
    }, 1000)
    event.preventDefault();
});

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

Employing ngModel in an option dropdown

I am having trouble passing an attribute from an API call to a submit function. I suspect it might have something to do with either the option select or how the input is being formatted. Encountering the error Error: No value accessor for form control wit ...

In PATCH requests, JSON data is not transmitted through Ajax

I'm attempting to send JSON data from the client to my server with the following code: $.ajax({ url : 'http://127.0.0.1:8001/api/v1/pulse/7/', data : data, type : 'PATCH', contentType : 'application/json' ...

Angular 2: Implementing a Universal CSS Style Sheet

Is there a way to include a universal CSS file in Angular 2 applications? Currently, I have multiple components that share the same button styling, but each component has its own CSS file containing the styles. This setup makes it difficult to make changes ...

The payload is properly returned by the Reducer, however, the component is receiving it as

In my current project, I am developing an application that involves fetching data from a firebase database. This particular database does not require authentication, and I have already adjusted the access rules to allow for public access. One of the actio ...

"Implement a feature that allows for infinite scrolling triggered by the height of

Looking for a unique solution to implement a load more or infinite scroll button that adjusts based on the height of a div. Imagine having a div with a height of 500px and content inside totaling 1000px. How can we display only the initial 500px of the div ...

What is the best way to pass the value of a selected option to an express server

<label for="exampleFormControlSelect1"> <strong>Please Select the Number of PDFs to Merge:</strong> </label> <select class="form-control" id="exampleFormControlSelect1"> <option name=" ...

Is it possible for two event listeners to operate concurrently?

Currently, I am programmatically generating unique ids for my div elements. These divs display a plus button as shown in the code snippet below: <div id="'+random_number+'" class="inc buttontest">+</div><div class="dec buttontest" ...

Instructions for populating a DataTable with JSON data while allowing for editing of rows

Hey there, looking for some expert advice, I've been experimenting with the datatable plugin and I'm curious if it's feasible to populate a table with row editing actions using ajax? This is the code snippet I currently have. It successfull ...

Randomly generated numerical value in input field

How can I generate a 15-digit number using JS code and then reduce it to just 5 or 6 digits in a text box? <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript ...

Learning about the intricacies of backend Node.js through Angular using GET requests

I am having trouble retrieving the query parameters from a frontend GET request on the backend side. I have attempted to use url and query, but still need assistance fetching the query on the nodejs side. Can someone recommend a method that would allow me ...

"Using JavaScript to Make Requests on Mobile Devices via HTTP

Greetings everyone, I have a query regarding implementing an endpoint api in my mobile application. For instance, suppose I have a server handling data and I want to notify my mobile application about new updates by sending a post request. Is this feasibl ...

Oops! Make sure to explicitly allow the dependency @types/html2canvas by adding it to the "allowedNonPeerDependencies" option

After installing the html2canvas package in my Angular library project, I encountered an error when compiling in production mode using the command ng build --prod. The specific error message is as follows: ERROR: Dependency @types/html2canvas must be exp ...

How to implement a for loop within a Vue.js method

Within Vuejs, I have a method that updates multiple variables based on user selection. methods: { updateChart(){ this.chart1.series[1].data = [this.$store.state.selectedcities[0].value[1]]; this.chart1.series[2].data = [this.$store.state.selecte ...

Parsing the JSON string from PHP using JSON.parse resulted in an unexpected and strange array

I've encountered a challenge when trying to transfer a JSON object from the server to client-side JavaScript. I fetched rows of data from a MySQL query and stored them in $result. Below is the code snippet: var json = '<?= json_encode($resu ...

What is the reason behind jqXHR.done() method returning the jqXHR object?

After running my $.post request, I noticed that the jqXHR object received contains a done function. What caught my attention is that this function seems to simply return the same jqXHR object: $.post(query, function(a,b,jqXHR) { jqXHR === jqXHR.done() / ...

What is the best way to customize the color of selected items in a RadComboBox using CSS?

I'm curious if it's possible to modify the "background-color" value for the selected items in a radCombobox. Below is the CSS code I've been using: (Despite being able to change other elements, I can't seem to alter the color of highli ...

What is the best way to broadcast video content from Google Cloud Storage to iOS Safari?

Currently seeking a reliable method to serve videos through Google Cloud Storage that is compatible with all browsers, including Apple devices. I am facing challenges trying to play videos on my website (Vue front end, node.js backend) that are stored in ...

Storing client-side data permanently in ASP.Net is a crucial aspect of web development

I am currently working on a project involving a Point of Sale (POS) system using ASP.Net. The web application functions perfectly when the client has access to the internet. However, I am exploring ways to enable the client to use the application offline w ...

Locate the chosen radio button within a group of <label> tags using the selenium webdriver

How can I iterate through all the label items within a div? There are multiple label tags with radio buttons inside. I'm using Selenium WebDriver and need to identify the selected radio button. Here are the two things I need to accomplish: Determine ...

Change button to an ajax spinner when it is clicked using jQuery

$(".post-btn").html("<img src='../images/loader.gif' />"); Why isn't this code working? I know I have the correct selector because when I tried $(".post-btn").text('test'), it worked. I want the text of the button to change ...