Using jQuery to duplicate a div multiple times when scrolling

I'm looking for a way to continuously duplicate the contents of a div as I scroll, creating the illusion of an infinitely scrolling page. My current markup looks like this and you can also find a working example in this fiddle https://jsfiddle.net/guht49La/:

var inserted = false
$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  if (scroll >= 800 && !inserted) {
    var $button = $('.hd').clone();
    ($button).insertBefore('.ap');
    inserted = true;
  } else {

  }
});

While this code only inserts it once, I am aiming to have it continue inserting every 800px (for instance) to create the continuous scrolling effect. Any suggestions on how to achieve this would be highly appreciated!

Answer №1

This method is effective for implementing scroll functionality

let inserted = false;
$(window).scroll(function() {
  let scroll_position = $(window).scrollTop();
  if (scroll_position >= 800) {
    let $button_clone = $('.hd').clone();
    ($button_clone).insertBefore('.ap');
    inserted = true;
  } else {

  }
});

Answer №2

I'm not entirely sure, but maybe you could try the following approach:

let autoScroll = 500;
$(window).scroll(function() {
  let scrollHeight = $(window).scrollTop();
  if (scrollHeight >= autoScroll) {
    let $newButton = $('.header').clone();
    ($newButton).insertBefore('.footer');
    autoScroll += 500;
  } else {

  }
});

Answer №3

Although the functionality is working, it only clones the div once because you set the inserated variable to true after inserting the initial clone. To ensure continuous cloning, you should remove that line:

var inserated = false
$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  if (scroll >= 800 && inserated == false) {
    var $button = $('.hd').clone();
    ($button).insertBefore('.ap');
    // inserated = true;
  } else {

  }
});

Note that inserated = true; has been commented out.

However, this code may generate an excessive number of clones, so I recommend implementing a more controlled approach for inserting based on scrolling position as suggested in Nat Karmios' answer.

Answer №4

After reviewing multiple solutions, I have come up with a slight variation based on the response from jbmartinez. In my approach, I have eliminated the use of the inserated variable and instead relied on classes to identify elements for cloning:

$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  if (scroll >= 800) {
    var $button = $('.hd').not(".cloned").clone();
    $button.addClass("cloned");
    ($button).insertBefore('.ap');
  } else {

  }
});

One thing to keep in mind is adjusting the scrolling marker according to the specific requirements.

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

What sets minifying CSS apart from compressing CSS?

Recently, I was focused on enhancing my website's performance and decided to run a google developer performance test. The results were positive overall, but the google analyzer recommended compressing the CSS files for even better performance. Up unt ...

Tips for creating a consistent vertical divider height between columns in bootstrap

I've encountered similar queries before, but the responses provided were not quite what I needed. While one answer came close to my desired outcome, it led to other complications that I am now facing. My main challenge is maintaining consistent vertic ...

Having trouble getting a response when using formidable in Next.js?

I am working on uploading a file from the front end to my GCP workflow, and everything seems to be functioning correctly. However, I am consistently encountering an issue where the API resolved without sending a response message appears. I attempted to r ...

Keep one row in a grid with five columns in Bootstrap

After trying out the code snippet from this Stack Overflow thread, I noticed that when I expand the screen to full size, column 5 moves to the next line on xs resizing. Is there a method to keep all columns in a single row even when the screen is resized ...

Using Ajax and PHP to Trigger a Forced Download

I am trying to develop a download script that enables the Force Download of JPGs. Below is my PHP script: <?php header("Pragma: public"); // required header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); ...

Combining Different Fonts in a Single CSS File

Is there a way to incorporate multiple fonts in a CSS file? I attempted the following method, but it's not producing the desired outcome. @font-face { font-family: 'Inspira_Reg'; src: url('http://myfonturl.com'); } @font- ...

How can we simplify this React component to reduce its verbosity?

After creating a test project to delve into react, react-router and react-redux, I revisited the Settings.jsx file. Now, I am pondering on how to streamline it and reduce potential errors. import React, { Component } from "react"; import { connect } from ...

Can you explain the contrast between the functions 'remove' and 'removeChild' in JavaScript?

I have recently coded an HTML page in order to gain a better understanding of how element removal functions. Code: <html> <head> <script> var childDiv = null; var parent1 = null; var parent2 = null; function ...

Discover a method to retrieve all recommended strings based on a search query using JavaScript

I have two strings: one containing all the values of countries and the second string that I entered when searching for a country. Now, I am looking to retrieve all results that contain "In", such as India and Indonesia. For example, if I search for "IN" ...

What is the best way to pass the value of a selected option to an express server

<label for="exampleFormControlSelect1"> <strong>Please Select the Number of PDFs to Merge:</strong> </label> <select class="form-control" id="exampleFormControlSelect1"> <option name=" ...

Issues with JSPDF and AutoTable

I've been trying to merge the "TABLE FROM HTML" with a "Header" without success. I looked at some examples and managed to make them work separately, but not together. Whenever I attempt to combine the two, I encounter issues... Can you point out what ...

Omit specific module from a webpack 4 chunk

Is there a way to exclude a specific module from being included in a chunk using webpack 4? For example, let's say I do not want lodash to be included in the vendor file at all costs. How can this be achieved? Here is the current configuration: spli ...

Troubleshooting Angular directives and the complications of closures

I am facing a problem with this specific directive: @Directive({ selector: '[imgTest]', }) export class ImgTest implements AfterViewInit, OnDestroy { private originalImage: HTMLImageElement; private secondImage: HTMLDivElement; construc ...

How about implementing Foreign Key with getters and setters in Sequelize?

Hello there! I recently started working with sequelize and ran into an issue. I added getters and setters to my model, but when I tried adding a foreign key, it didn't get created. Strangely enough, the foreign key only appeared after I removed the ge ...

If I create an App with Phonegap, HTML5, and Websql, what happens to the app's data when the user restarts their mobile device?

My application utilizes HTML5's WebSQL to store temporary notes and bookmarks, which will later be synchronized with the server. I am curious whether data stored in WebSQL will be lost upon mobile restart or cache clear, similar to how browsers on ph ...

How can I attach the input value that has been selected to another div using Ajax AutoComplete for jQuery?

Greetings, I am currently utilizing the Ajax AutoComplete for jQuery library. Within this library, there are 2 demos available. In the first demo titled "Ajax auto-suggest sample (start typing country name)", when a country is selected from the dropdown, ...

transferring a value from php to javascript using a form's id

I'm facing an issue where I need to pass a dynamically generated ID from a form to JavaScript. <script type="text/javascript"> $(function() { $(".button-call").click(function() { var fld = "<?= $div_id;?>"; var test = $(fld).val ...

The sluggish performance of my website is being caused by the livereload process that was inserted into my index.hml file, causing it

Recently, I've noticed that this line of code is being inserted dynamically into my index.html file, either through Grunt tasks or directly from the server in Heroku. <script type="text/javascript">document.write('<script src="' + ...

The "src" attribute is missing from the image on the left side

I'm currently facing an issue with the src attribute in this code: An event updates the src based on a variable retrieved from a form. The image files cannot be renamed, so I must work with their existing names. The problem arises as all file names c ...

Customizing Bootstrap by incorporating my own external stylesheet

I've been working on learning Bootstrap and decided to challenge myself by trying to recreate this website: However, I'm encountering difficulties when it comes to overriding Bootstrap and incorporating my own custom font. I attempted to add a G ...