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

The intricacies of how Node.js handles asynchronous execution flow

I wanted to ask about the best approach for displaying data retrieved from MySQL. Do you think this workflow is correct? app.get('/demo/:id', function(req, res) { var query = csql.query('SELECT * FROM table_videos WHERE id=? LIMIT 1' ...

Encountering issue with jQuery - Ajax causing error 500 for select posts

Recently, I encountered an issue with the Ajax functionality on a live website. It was previously working perfectly fine, but suddenly started returning a 500 internal server error instead of the expected page. Oddly enough, I discovered that I could stil ...

Having trouble sending the information to Parse.com using the website

I am a beginner with the Parse database and I am currently working on implementing a code that allows users to sign up, with their information stored in the Parse database. However, I am encountering an issue where the values are not uploading as expected. ...

Notifying Users of JavaFX Applet Web Page Refresh and Closure

Is there a way to detect when a user closes or refreshes a web page with a JavaFX applet embedded in it? I need to perform some clean-up tasks in my code when these events occur. In the past, Java Applet had callback methods for this purpose. How can I ac ...

Text that only occupies a portion of the screen width

My unordered list (ul) contains three list items (li). The first li element displays the text "opptakskrav" and the last li element displays "ja". Can anyone explain why the text in my second li element does not use the full width and starts a new line hal ...

In PHP, it is essential to always complete the necessary information in form validation

I've been working on implementing JavaScript form validation, but I seem to be having trouble with testing for empty fields in the form. Whenever I submit a fully filled out form, it keeps asking me to fill in the blank fields. Here is the code I hav ...

It appears that the React MUI Grid is causing the page or its container to experience overflow issues

I'm utilizing Grid to maintain the organization of the entire page, but I keep encountering an overflow issue when adding multiple Grid items. This results in the scrollbar appearing even though the container size remains the same. Dashboard.tsx is pa ...

What steps can be taken to handle and proceed with any outstanding AJAX requests in the event a

I am currently working on a script to automatically refresh all CSS/JS files that are marked with the attribute-data when any changes occur on the server side. Initially, I attempted to achieve this using php and jquery/javascript but now I am focusing sol ...

The SVG icon displays properly when viewed on a local machine, but is missing when the website is deployed

Something strange is happening with my SVG sprites. Everything seems to be working fine when I test my code locally, but once deployed on Firebase, one of the SVG images fails to appear. What could be causing this issue? Below is the code for two SVGs: sm ...

The JavaScript functions are not loading within the onload event handler

I've got an HTML document that contains some Script sections. I've consolidated all the functions within a single Script Tag. Now, I want to be able to utilize these methods in both the onload and onclick events. Below is the HTML file with all t ...

The json_encode function in Javascript is not returning a valid value

I am facing an issue with a PHP array that I encode using json_encode and then pass to a variable in a JavaScript function. Even though the array seems fine after encoding, it appears as a valid JavaScript array. However, I keep receiving 'undefined&a ...

Transform an iOS WebView into a user-friendly ebook reader

Typically, in a webview, you can scroll vertically like a browser if the page is too long. However, I am interested in transforming this experience to mimic an ebook reader. Rather than scrolling down, I would like users to be able to swipe to the next pag ...

ng-class will not activate a custom directive

I have developed a custom AngularJS directive that should work on elements with the specified class name .collapse. However, when I apply this class using Angular's ng-class directive, the custom collapse directive does not get activated. Here is a ...

An image on the left side of a perfectly aligned text

I am currently working on aligning an image and text for a logo. However, I am having trouble justifying the second line to the width of the block. Here is the desired result: This is what I have tried: @import url(http://fonts.googleapis.com/css?famil ...

Structuring JavaScript in Rails' asset pipeline

Overall: What are the most effective strategies for structuring JavaScript within the Rails pipeline? Specifically: My JS files are growing rapidly and while I'm okay with including them in the main application.js bundle and using Sprockets to minify ...

Implementing jQuery UI toggleClass method to seamlessly alternate between two distinct CSS classes

My goal is to toggle between two CSS classes on a selector click using Jquery UI .toggleClass(), but unfortunately, it's not producing the desired toggle effect. $(".toggle").click(function () { $(".archivePosts .columns").removeClass( "l ...

"Exploring the challenges of implementing a jquerytools tooltip with AJAX

Currently, I have set up an ajax call to run every 15 seconds. The issue arises when the ajax call disables the tooltip if it's open at that moment for a particular item. This results in the destruction of only the tooltip being displayed, leaving oth ...

Selecting HTML5 data attributes using jQuery

There is a button on my page with multiple data attributes, and I am trying to hide it by selecting it based on its class and two specific data attributes. <a href='#' class='wishlist-icon' data-wish-name='product' data-wi ...

How to Retrieve an Image from a Server Using Node.js and Express

I have successfully implemented a feature to upload images to my server and then store them in the Postgresql database. However, I am facing an issue when trying to display an image on the browser by entering the URL like "http://localhost:5000/photoURL/ ...

Organizing Angular project folders with the help of Node.js and Jade

I've been exploring different folder structures to ensure scalability as my project grows. While I found some useful resources, such as this one, I'm still struggling with how to actually implement these suggestions. Currently, I've adopted ...