`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

Error: Cannot access property 'tb' of an undefined value

While running the Application, I encountered an error in the declaration of constants.ts file where I was assigning data from a json file to constant variables. In the json file named object.json, I had some data structured like this: { "furniture": { ...

Deleting specialized object using useEffect hook

There's a simple vanilla JS component that should be triggered when an element is added to the DOM (componentDidMount) and destroyed when removed. Here's an example of such a component: class TestComponent { interval?: number; constructor() ...

What are the reasons behind the pagination with numbers not functioning properly in Vue?

I've encountered an issue with my Vue application using Vuex while implementing pagination. The problem lies in the fact that the events stored are not being displayed, and neither are the page numbers for pagination. Another issue is that the paginat ...

Unable to differentiate between .jsx and .js files

Here is the content of my JavaScript file: var React = require('react'); export default class AmortizationChart extends React.Component { render() { var items = this.props.data.map(function (year, index) { ret ...

A Guide to Effortlessly Implementing moment.js into a React TypeScript Application

I'm attempting to implement code splitting and one of the specific packages I want to separate into its own chunk is moment.js. Here's how I'm doing it: const myFunc = async (currentNumber) => { const moment = (await import('momen ...

Passing a JavaScript variable to a URL parameter can be achieved by

Can anyone advise me on passing JavaScript string variables and displaying them in the URL? For instance, let's say the URL is "xyc.com". Upon populating a variable (a), I wish for that variable to appear in the address bar as URL = "xyc.com/?a=". Cur ...

Can a function be embedded within a React render method that includes a conditional statement to update the state using setState()?

My application randomly selects three values from an array found within defaultProps and then displays these values inside div elements in the return JSX. It also assigns these values to properties in the state object. I am facing a challenge where I need ...

Transform ISO-8859-1 encoding into UTF-8

Recently, I encountered an issue while sending a HTTP request using jQuery's ajax. The server, unfortunately, returns the response in ISO-8859-1 format while my page is set to UTF-8. This discrepancy causes some characters to become unreadable. How ...

The input type '{}' does not match the expected type 'Readonly<IIdeasContainerProps>'. The property '...' is not found in the type '{}'

Having recently started using TypeScript, I'm encountering some issues when attempting to execute this code snippet. Error The error message reads as follows: Failed to compile 13,8): Type '{}' is not assignable to type 'Readonly &l ...

Angular BehaviorSubject is failing to emit the next value

I am facing an issue with a service that uses a Behavior subject which is not triggering the next() function. Upon checking, I can see that the method is being called as the response is logged in the console. errorSubject = new BehaviorSubject<any> ...

Is it possible to maintain a div's height in proportion to its width using CSS?

Is it possible to set a CSS variable so that my div's height is always half of its width, and the width scales with the screen size (in percentage)? <div class="ss"></div> CSS: .ss { width: 30%; height: 50% of the width; } This ...

javascript Incorrectly using location.reload will not refresh the page as intended

My goal is to refresh a page every time a user clicks a button so the page reverts back to its original source code. However, I am facing an issue where the location.reload() function is being executed after the code instead of at the beginning. btn.addEve ...

Ways to avoid browser refresh when uploading files in React applications

I'm working with a simple file upload form in React using hooks. import React, { useState } from 'react'; import { FlexContainer } from '@styles/FlexContainer'; const TestUpload = () => { const [file, setFile] = useState<F ...

Using jqgrid to generate a hyperlink that corresponds to the data's value

I am working with a grid setup similar to the one below: $("#list").jqGrid({ url:'listOpenQueryInXML.php', datatype: 'xml', colNames:['Id','name1', 'name2', 'status', 'type' ...

Error encountered in my JavaScript file - Unexpected Token < found on line 1 of the loadash.js script

I am right at the end of creating a sample dashboard with charts using dc.js, but I have hit a roadblock with one error remaining. This error is causing an issue. Unexpected token < on line 1 for loadash.js. The loadash.js file is valid, but for som ...

Transform the outcome of Request() into a variable

I'm currently working with the following code snippet: request('http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=Gamma Case', function (e, r, body){ var req_data = JSON.parse(body); conso ...

Submitting form data including file uploads using AJAX

Currently, the file is being sent via AJAX using the following code: var fd = new FormData(); //additional actions to include files var xhr = new XMLHttpRequest(); xhr.open('POST', '/Upload/' + ID); xhr.send(fd); In ...

Can multiple `npm install` commands run at the same time?

Is it possible to have concurrent runs of npm install, or will they conflict on shared resources and create potential race conditions? Analyzing the code might not provide a clear answer, but for those working on developing npm, this is likely an implicit ...

Trouble in connecting local CSS stylesheet

I am facing an issue with adding my .css file to my project. Even though I have tried various methods, the styles are not being applied properly. When I directly embed the style code in HTML, it seems to work fine. This leads me to believe that the proble ...

"Utilizing Mootools to dynamically load content using a custom function

I am currently utilizing mootools and have a desire to load content into a div labeled response. To achieve this, I use the following JavaScript code: $('response').set('html', content), where 'content' is a variable containin ...