`Cannot Get jQuery ScrollTop Function to Work for 2nd Element`

Having trouble with an issue. Let me explain.

I implemented a scrollTop Jquery on page load that scrolls down after a delay to prompt user action. However, I'm facing a problem where another scrollTop doesn't work after clicking buttons "#b3,#b3b" and fails to scroll to the bottom of the page as intended.

The desired behavior is for it to scroll to the element with the class .comp at the bottom, but it either doesn't scroll all the way or just moves slightly downwards.

If you have any insights on how to make the page scroll to the bottom element successfully the second time after clicking the button, please share them!

$(document).ready(function () {
    $('html, body').delay(1500).animate({
        scrollTop: $('.button').offset().top
    }, 'slow');
   // Further Javascript code here...

});
* {
// CSS styles here...
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap">
    <div id="header"><h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</h1>
    </div>
  <div id="content">
    <div id="graphic"><img src="#" alt="" height="500px" width="300px"></div>
    <div id="text">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
        
      <div class="actionbox" id="a3" style="display:block">
                <h2><strong>Question 3:</strong></h2>
                <div class="butbox">
                    <div class="button buttxt" id="b3"><a href="#/">YES</a></div>
                     <div class="buttonr buttxt" id="b3b"><a href="#/">NO</a></div>
            </div>
     </div>
      <div class="actionbox" id="a4">
        <div id="bar"><div id="percentage"></div></div>
               <h3 id="r1">step1...</h3>
               <h3 id="r2">step2...</h3>
               <h3 id="r3">step3...</h3>
               <h3 id="r4">step4...</h3>

               // More HTML content here...

</div>
    </div>
  </div>
</div>

Answer №1

Instead of relying on fixed time delays for animations, a more effective approach is to sequence them relative to each other by embedding functions within each other. This ensures that the element being scrolled to will be visible at the appropriate moment, avoiding any issues with hidden elements (which may have been causing your problem).

Take a look at this fiddle for reference.

I made some adjustments to the timing, but you'll get the general idea. Here's how the modified code would appear:

$("#b3,#b3b").click(function(){
  $("#a3").fadeOut('fast'),$("#a4").fadeIn('slow');

  $("#bar").width(0);
  $('#r1').show(500);
  $("#bar").delay(150).animate({width: '+=40%'},2000, function() {
    $('#r1').hide(500);
    $('#r2').show(500);
    $('#rb1').show(500);
    $("#bar").animate({width: '+=20%'},2000, function() {
      $('#r2').hide(500);
      $('#r3').show(500);
      $('#rb2').show(500);
      $("#bar").animate({width: '+=20%'},2000, function() {
        $('#r3').hide(500);
        $('#r4').show(500);
        $('#rb3').show(500);
        $("#bar").animate({width: '+=20%'},2000, function() {
          $('#r4').show(500);
          $("#r5").show(); // make sure the element is visible before scrolling to its child
          $('html, body').animate({
            scrollTop: $('.comp').offset().top
          }, 'slow');
        });
      });
    });
  });
});

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

Tinymce editor does not display icons as expected

I am attempting to create a custom styled list that is editable with tinymce. The list-items are using Material-Check-Icons as bullet-points, which are added as css-pseudo-elements ::before. This setup works well, but when I integrate tinymce (v5) into the ...

How to Use jQuery Post Method to Submit a Form Without Redirecting

I am looking to enhance the user experience of my form by preventing it from reloading upon submission. Specifically, I want to trigger the call to index.php when the submit button named "delete-image" is clicked in the scenario outlined below. It's i ...

What is the reason behind "Script" being considered the offspring of "Body"?

Unfortunately, I struggle with HTML/CSS/Javascript and am just trying to get through my exams. I have the code snippet below: <script> window.onload=function() { var c = document.body.childNodes; var txt = ""; var i; for ...

Incorporating react-intl-tel-input into your project: A step

Greetings, I am currently delving into the realm of ReactJS and am tasked with incorporating react-intl-tel-input to capture phone numbers from around the globe. However, during the integration process, I encountered some obstacles. When I input this code: ...

Is it true that Javascript does not allow for saving or outputting actions?

After coming across this question, I discovered a way to extract a specific element from a Google translate page using Javascript. However, I also learned that it is nearly impossible to directly save something to the clipboard in Javascript without user i ...

TypeError: Unable to execute products.map as a function

I'm encountering an issue where product.map is not functioning as expected, despite trying multiple fixes found online. Additionally, when I console.log(response.data), it shows a successful response. Using React version 7.0 constructor () { ...

After the ajax request is finished, make sure to remove the previous .on()

I have a scenario where I am dynamically loading a partial page using ASP.NET-MVC after making an Ajax request with Ajax.BeginForm. On this loaded partial page, there are some jQuery .on event handlers that cannot be relocated to another place. They rely ...

I'm encountering a "confirm" error within the data table. Any suggestions on how to resolve this issue?

When I try to use two datatables columns in confirm, an error occurs when the text 'do you want cancel?' is displayed. The issue seems to be with the text itself and not the code. How should we go about fixing this problem? This is my current cod ...

How to prevent selection of certain days in an Angular date input

I need help with my Angular component that includes an input date field. I am trying to figure out how to disable all past dates and also a specific range of future dates, such as those between 2023-10-15 and 2023-10-23. Is there a way to achieve this func ...

Exploring the power of NodeJS modules through exports referencing

Encountering difficulties referencing dynamic variables related to mongoose models based on user session location value. Two scripts are involved in this process. The first script is called location.js & reporting.js In the location.js script: module.ex ...

Using Typescript: invoking static functions within a constructor

This is an illustration of my class containing the relevant methods. class Example { constructor(info) { // calling validateInfo(info) } static validateInfo(info):void { // validation of info } I aim to invoke validateInfo ...

Converting XML hierarchy into a flat HTML table using XSLT

Looking for a way to transform hierarchical XML into an HTML table? Here's the challenge: <node text="a" value="1"> <node text="gga" value="5"> <node text="dh" value="9"> <node text="tyfg" value="4"> < ...

Alter the app's entire background color in React.js with a button click

I am facing an issue with changing the background color of my entire React App when a button is clicked. Currently, I am able to change the color of the button itself but not the background. I have imported the App.css file into my project and I am looking ...

Error: Collision detection in Three.js console output

I am attempting to create a collision detection system using Three.js (a WEBGL library). However, I keep encountering an error stating "cannot call method multiplyVector3 of undefined". Is there anyone who can help me identify what I may be doing incorrec ...

Experiencing a missing handlebars helper error when utilizing a helper within partials in express-handlebars

I have set up custom helpers using express-handlebars like this: const { create } = require("express-handlebars"); // Configuring the handlebars engine const hbs = create({ helpers: require("./config/handlebars-helpers"), }); app.engi ...

How to remove a specific type from a generic type in Typescript without using Exclude<>?

I am looking for a solution to prevent my function from working with Moment objects when storing values in local storage. Currently, the function dynamically stringifies and stores values, but I want to exclude Moment objects from being processed. Here is ...

What is the method for replacing browser bundle sources using Rollup?

Is it possible to use rollup to swap out a specific source with another source in an NPM package when creating a browser bundle? The source in question is loaded dynamically using import('./relativeFile.js') (I need this to be replaced). I attem ...

Issue encountered with AJAX multiple image uploader

I'm attempting to create an PHP and JavaScript (jQuery using $.ajax) image uploader. HTML: <form method="post" action="php/inc.upload.php" id="upload-form" enctype="multipart/form-data"> <input type="file" id="file-input" name="file[]" a ...

Guide to implementing endless ajax scroll pagination using Codeiginiter

I am attempting to implement infinite ajax scroll pagination on my blog, but unfortunately I am encountering an issue. The error message "server not responding..." keeps appearing despite troubleshooting efforts. Below is the code snippet being utilized: ...

Is there a comparable solution like Fabric in Javascript or Node.js?

One thing that I really appreciate about Fabric is how it simplifies the deployment process to multiple servers, especially with its strong support for SSH. But since our project is based on node.js, it would be ideal if we could achieve a similar function ...