When scrolling, a new page loads seamlessly

Recently, I came across a website that has an interesting feature where new content is loaded automatically while scrolling, seamlessly appending to the existing page.

What's more fascinating is that not only does the content change, but the URL also updates as you scroll.

I am intrigued by this functionality and would like to learn how to incorporate it into my own website. The website that inspired me is matt. Simply by scrolling down, you will see the concept of an infinite scrollbar in action along with the automatic changing of the URL address bar.

Answer №1

To add dynamic content to an existing page from a database as the user scrolls, you can make an AJAX call on scroll and control the number of calls using a throttle function. This function will ensure that the AJAX call is only served a maximum of once within a specified wait time interval.

var myajax = _.throttle(/*your ajax call goes here*/, wait/*time in ms*/);

The _.throttle() function is part of the underscore.js library. If you prefer not to use this library, you can utilize a custom version of throttle:

function myThrottle(func, wait, leading) {
  var lastCall = 0, timeout = null,

  execute = function() {
    clearTimeout(timeout);
    timeout = null;
    func();
  };

  return function() {
    var currentTime = new Date().getTime();
    if (leading && (lastCall == 0 || (currentTime - lastCall) > wait)) {
      lastCall = currentTime;
      func();
    }

    else if (!leading && !timeout)
      timeout = setTimeout(execute, wait);
  };
}

In the above snippet, the third argument leading determines whether the call should be made at the beginning or end of the wait duration. Setting it to true triggers the call at the start, blocking further calls until the wait period ends.

Answer №2

Below is an example of how you could implement this functionality:

var pageHeight = $(document).height(), // storing document height
    currentPage = 0; // current page number

$(document).on('scroll', function () {
    // if the window scroll position exceeds document height minus 300px,
    // send an ajax request and add the result to a container
    if($(window).scrollTop() > pageHeight - 300) { 
        $.ajax({
            type: "POST",
            url: "some.php",
            data: { page: currentPage },
            success: function (data) {
                $('.my-container').append(data); // adding result to container

                // store new document height
                pageHeight = $(document).height();

                currentPage += 1; // update page number

                //update url in address bar
                window.history.pushState({},"","/page/"+currentPage); 
            }
        });
    }
});

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

Understanding how to access POST content in Meteor.js is an important aspect

In my Meteor app, I am trying to retrieve data using POST requests. Here is the code snippet I am using on the server side: __meteor_bootstrap__.app.stack.splice (0, 0, { route: '/input', handle: function(req, res, next) { req.on(' ...

Prevent the creation of references to objects passed as function parameters in a separate list

I'm facing an issue with modifying items from an array and adding them to a new list of objects. The problem arises when I make changes to the item in the new list, it also reflects those changes in the original array. It seems like there is some ref ...

Is there a way to align the image to the left within the div contained in my header section?

I am facing an issue with positioning the logo in the header section of my website. It appears correctly on the left side for tablet and mobile versions, but on desktop, it does not align to the corner as desired. I tried adding a right margin, but I belie ...

Exploring the functionality of dimensions in d3 parcoords

I am diving into the world of d3 and experimenting with Behold, a simplistic example directly from the website. <script src="http://d3js.org/d3.v3.min.js"></script> <script src="d3.parcoords.js"></script> <link rel="stylesheet" ...

Exploring the depths of JavaScript JSON elements

After processing my PHP code, it generates a JSON output that contains multiple entries in the same structure. Here is an example with two entries: { "0": { "campaign_id": "31", "title": "new title", "description": "new descrip ...

Adjust the image size using CSS within the containing outer div

I am trying to adjust the width of an image using css within typo3. Unfortunately, I only have access to the outer div container which is the custom border of the content element. To make the change, I added the following line to my css file: .Bild-Starts ...

mastering the chrome api within your redux-saga workflow

Currently, I'm working on creating a 'get_current_url' function using redux-saga in my project involving a Chrome extension built with React.js. In order to obtain the current URI, I need to utilize the chrome.tabs.query API. Below is the sn ...

AJAX allows developers to declare variables within their code to

Here is a snippet of my JavaScript code: $(\"img.agree\").click(function() { var follow_id = $(this).attr(\"id\"); var user_id = $(\"img.user_id\").attr(\"id\"); $.ajax({ type: \"POST& ...

Click event not triggered when transitioning to Service section in Thinkster tutorial

I've been following a tutorial on MEAN stack development () and I encountered an issue after incorporating Angular Services. For some reason, the function incrementUpvotes stopped working and I'm struggling to identify the cause. Since I'm r ...

What is the best way to assign attributes to all items in an array, excluding the currently selected one?

I need to implement dynamic buttons in my HTML document while a JavaScript class is running and receives a response from the backend. I am using jQuery and vanilla JS, and have included an example below to demonstrate this functionality. The goal is to dis ...

css: text not enclosed by a span tag

I created an HTML-CSS demo with two simple span tags. I added some content to each span, and applied the same CSS code to both. Surprisingly, the content of the right span goes beyond the border, while the content of the left span stays within the border. ...

Managing headers for localhost with Access-Control-Allow-Origin

I've run into a challenge with my React app. I'm making endpoint calls to different servers and have withCredentials set to true to include a token/cookie in the requests. The issue arises when trying to make this work seamlessly on localhost. S ...

Should I incorporate PHP/HTML code or opt for using a function instead?

I'm currently exploring the most effective method for integrating HTML/PHP code into various pages, such as headers, footers, and other repetitive sections. Would it be better to use include_once(php file) (even if it's used multiple times on a ...

Uncertain about how to transfer data between server and client in Next.js?

I'm currently grappling with understanding the proper method of exchanging data between server-side and client-side components in NextJS 13. To simplify my learning process, I have created a basic scenario. In this setup, I have two functions that pe ...

Send information through a form by utilizing a personalized React hook

I'm having difficulty understanding how to implement a hook for submitting a form using fetch. Currently, this is what I have. The component containing the form: const MyForm = (): ReactElement => { const [status, data] = useSubmitForm('h ...

Prevent Image Distortion in HTML and CSS

Is there a way to prevent a background image from stretching in html/css? Take a look at the current code below, where the image behind a button appears like this: #backImage6{ /*@editable*/background-image:url(https://images.unsplash.com/phot ...

Display open time slots in increments of 15 minutes on Fullcalendar

Currently, I am utilizing the fullcalendar plugin with the 'agendaweek' view. My goal is to showcase the available time slots as clickable and highlight the busy ones with a red background. Handling the highlighting of busy slots is not an issue ...

What is the best way to arrange elements above and below each other in a single flexbox container?

Currently, I am facing a challenge aligning the number 238,741 and the letter N in Number. There is a padding between the Prize Pool div and the Number Active div. All of these elements are enclosed within a parent container with display set to flex and fl ...

The function document.getElementById is unable to select multiple elements simultaneously

I've been tackling a loading issue. I have a visible div, #loading, and multiple hidden divs, #message. I also have a JavaScript function. function loading() { setTimeout(function() { document.getElementById("loading").style.display = " ...

Arrow function utilized in string rendered component

Hello everyone, I could use some help with the following code snippet: rowRenderer = (e) => { debugger; return e.data?.fileName ? '<a class="documentLink" onclick={() => \'' + console.log('\ ...