Navigate down to the lower section of the webpage once the fresh container has finished loading

Let's get straight to the point.. I have got 2 containers, each with a height of 100vh. The second container is supposed to be displayed when a button in the first container is clicked. However, the issue arises when the button click event function also includes the line

window.scrollTo(0,document.body.scrollHeight);
, causing the scroll to jump to the bottom prematurely. This happens because JavaScript is asynchronous, and it doesn't wait for the information from an API (which takes some time) to load before executing the scroll function. How can I resolve this problem?

Edit: Here are some additional details.. The visibility of the second container depends on a boolean variable which is set to true in the callback function.

This is how I achieve that:

.then(res => {
    res.forEach(data => {
        ...
    }

    if (Object.keys(res).lenght > 1) {
        this.isTrack = false
        this.displayTracks = true   <!-- Second container's boolean variable -->
        window.scrollTo({top: 5000, behavior: 'smooth'});
    }
})

Answer №1

It is important to note that in asynchronous javascript, you must wait for events to complete before proceeding. To address this issue, callback functions are commonly used in javascript. These functions are triggered when an asynchronous call is completed. By navigating to the end of the page within your callback function, you can effectively avoid synchronization concerns.

Answer №2

To handle this issue, one possible solution is to utilize the scrollTo function within the API request callback, or employ async/await to ensure that the scroll action occurs only after the request has been completed.

An example of triggering it within the API request callback could be as follows:

fetch('someUrl')
   .then(() => {
     window.scrollTo(0,document.body.scrollHeight)
   });

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

Steps for toggling between enabling and disabling the 2 instances of bvalidator

Running on my form are two instances of bvalidator found at . The first instance validates the entire form, while the second instance only partially validates the same form. In total, the form contains 2 buttons: The first button saves form data upon va ...

Eliminate the AM and PM options from the input time selection dropdown menu in HTML

https://i.sstatic.net/wKeQk.png Is it possible to eliminate the AM / PM option from the input time format dropdown? The form builder currently uses a 24-hour format that includes the AM / PM field. ...

The server is expecting the 'Access-Control-Allow-Credentials' to be true in the CORS request made after the preflight request

Let's keep the questions sweet and clean, as much as possible. I need to send CORS as a requirement request using $.ajax. Here is how it looks: $.ajaxSetup({ beforeSend: function (jqXHR, options) { options.url = Utils.setUrlHostn ...

The combination of Protractor, Selenium, and Docker with Chrome results in a WebDriverError: an unknown issue occurred where Chrome failed to initiate

I followed the steps outlined in this tutorial http://www.protractortest.org/#/tutorial and https://github.com/angular/protractor-cookbook/tree/master/protractor-docker (I recently switched from using separate selenium hub and node to ) I have config ...

What is the process of loading a table onto various webpages using HTML?

I am in the process of developing a website to showcase reports in table format, all retrieved from an SQL database using PHP. While the pages are functional, they suffer from slow loading times when dealing with a large amount of data, typically more than ...

Creating a String Array and linking it to an Input Field

I'm currently working on a code that involves mapping through an array of strings using observables. My objective is to display the value from this array inside an input field. However, despite being able to view the array in the console, I encountere ...

Retrieving data using the GetJSON method consistently returns identical values

Here is the code I have written: $(document).ready(function () { $.getJSON("data.json", function (data) { var user_Data = ""; $.each(data, function (key, value) { user_Data += '<p class="user">' + value.na ...

Is the Kendo cascade-from trigger happening before it should?

Utilizing Kendo with angular.js, I am experiencing an issue where the model does not update when the event fires after making a selection in the first dropdown list... <input kendo-drop-down-list id="ddServiceLocations" k-options="ddServi ...

Is it possible to assign a deconstructed array to a variable and then further deconstruct it?

Is there a way to deconstruct an array, assign it to a variable, and then pass the value to another deconstructed variable all in one line of code? Take a look at what I want to achieve below: const { prop } = [a] = chips.filter(x => x.id == 1); Typic ...

Unable to display objects in the console window debugger for debugging purposes

When attempting to print the objects in the console window using the code below, I am receiving an "Undefined" error message. Any advice on how to resolve this issue? var details = [ { name:"Anita", age:"20" },{ name: "H ...

SharePoint List utilized to create a vertical stacked bar chart

I am currently working on creating a stacked bar chart using SharePoint complex list data with REST and JavaScript. The challenge I'm facing is that I'm having difficulty obtaining the proper data sets. My scenario is as follows: I have a ShareP ...

Link up each query with every php echo

Suppose I have the following PHP code: $logger = $_SESSION['logger']; $postquery = $con->query("SELECT * FROM posts ORDER BY id DESC LIMIT 5"); while($row = $postquery->fetch_object()){ $posts[] = $row; } And then, this section of ...

Ensure the dark mode switch CSS remains consistent when navigating to different pages

I have been working on a code to toggle between dark and light mode on a webpage. While it works fine within the current page, the issue arises when I navigate to another page or refresh the current one - the mode resets back to default (light). How can I ...

Is it possible to assign a specific color and font style to a title tag?

Is there a way to style a page title with a different color and font in the page tab? For example: title{ color: red; font: 12px tahoma;} I thought it would be interesting to incorporate into websites. I attempted the code above in my CSS file, but it di ...

I want to know how to use PHP to count the number of occurrences of a specific value in a MySQL table and then echo the count. Can you help me with

I am working with a MySQL table that contains several varchars in one column. My goal is to determine the number of times a specific varchar appears in this column and then display that count using PHP. Can anyone provide me with the necessary SQL code to ...

Using PHP to pass variables to an external JavaScript file

I have come across the following code snippet: PHP <?php include("db.php"); ?> <html> <head> <title>Title</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/j ...

Avoiding HTML in JavaScript: Tips and Tricks

My application generates numerous elements dynamically based on server data in JSON format. This process involves embedding a significant amount of HTML directly within my JavaScript code, leading to pollution and making it increasingly challenging and l ...

fancybox fails to display overlay at the bottom of the page when the popup's length exceeds that of the original page

Currently, I am utilizing Fancybox on a website and experiencing smooth sailing except for one issue... The problem arises when the page fits on a single screen, but the popup window is larger than the screen, resulting in the overlay only being shown for ...

router-link-active does not get activated on routes that match

As I continue my journey of learning Vue, I have encountered a situation that requires me to display a link as active for a matching route. For example, I have a route /programs, which correctly highlights the Program link as active. However, I also want / ...

What is the best approach to modifying array elements using onChange and hooks in React?

I'm struggling to implement something simple, and the solutions I've found so far don't quite address my specific issue. Here's the state in question: const [formFields, setFormFields ] = useState({ formTitle: '', fiel ...