How to identify when a user has reached the bottom of a div element in HTML using JavaScript

Recently, I ventured into the world of JavaScript and attempted to create a script that can detect when a user reaches the end of a div tag. After some searching, I came across this code snippet:

<!DOCTYPE HTML> 
<html> 

<head> 
  <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> 
</script> 
</head> 
<style type="text/css">
.container{width:200px;height:150px;overflow:auto;}
</style>
<body>
  <div class="container">
Lorem ipsum dolor sit amet <br>
Consectetuer augue nibh lacus at <br>
Pretium Donec felis dolor penatibus <br>
Phasellus consequat Vivamus dui lacinia <br>
Ornare nonummy laoreet lacus Donec <br>
Ut ut libero Curabitur id <br>
Dui pretium hendrerit sapien Pellentesque <br>

</div>

</body>

    <script type="text/javascript"> 
jQuery(
  function($)
  {
    $('.container').bind('scroll', function()
    {
      if($(this).scrollTop() + $(this).innerHeight()>=$(this)[0].scrollHeight)
        {
           alert('end reached');
        }
     })
  }
);
    </script>
  
</html> 

This code worked perfectly for me. However, when I made some changes like:

  1. Removing the class
  2. Replacing the class name with an ID

The updated script looks like this:

    <script type="text/javascript"> 
jQuery(
  function($)
  {
    $('#myExample').bind('scroll', function()
    {
      if($(this).scrollTop() + $(this).innerHeight()>=$(this)[0].scrollHeight)
        {
           alert('end reached');
        }
     })
  }
);
    </script>

Here is the modified body section:

<body>
  <div id="myExample" style="margin-bottom: 1000px">
Lorem ipsum dolor sit amet <br>
Consectetuer augue nibh lacus at <br>
Pretium Donec felis dolor penatibus <br>
Phasellus consequat Vivamus dui lacinia <br>
Ornare nonummy laoreet lacus Donec <br>
Ut ut libero Curabitur id <br>
Dui pretium hendrerit sapien Pellentesque <br>

</div>

</body>

Unfortunately, the updated code does not work anymore. The issue might be because it no longer has the .container class. I'm in need of assistance. https://i.sstatic.net/jDXKW.png

Answer №1

First off, avoid using the bind() function as it is considered outdated. Opt for the on() method instead:

$('#myExample').on('scroll', function()
...

Next, in order to enable scrolling, you need to adjust the size of the container relative to the text content. To do this, enclose the text within an additional div element, assigning it the unique id of myExample_text. This inner div should have a specific height set to 1000 pixels:

<div id="myExample_text" style="height: 1000px;">
...
</div>

Finally, ensure that the parent div (#myExample) has the smallest possible height for efficient scrolling.

For a comprehensive solution, refer to the following code snippet:

<!DOCTYPE HTML> 
<html>
   <head>
      <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> 
   </head>
   <body>
      <div id="myExample" style="width: 200px; height: 150px; overflow: auto; margin-bottom: 1000px">
         <div id="myExample_text" style="height: 1000px;">
            Lorem ipsum dolor sit amet <br>
            Consectetuer augue nibh lacus at <br>
            Pretium Donec felis dolor penatibus <br>
            Phasellus consequat Vivamus dui lacinia <br>
            Ornare nonummy laoreet lacus Donec <br>
            Ut ut libero Curabitur id <br>
            Dui pretium hendrerit sapien Pellentesque <br>
         </div>
      </div>
   </body>
   <script type="text/javascript"> 
      jQuery(
        function($)
        {
          $('#myExample').on('scroll', function()
          {
            if($(this).scrollTop() + $(this).innerHeight()>=$(this)[0].scrollHeight)
              {
                 alert('end reached');
              }
           })
        }
      );         
   </script>
</html>

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

Send the form using information from an array based on its current position

I have a form within a list that is submitted using a function. Each item in the list contains a postId and userId. The postId and userId are utilized in the input fields of the form. An Issue Arises The problem occurs when submitting the form as it al ...

Tips for reducing the size of input-group-addon in Bootstrap

https://i.sstatic.net/V7ywZ.png <div class="time input-group"> <span class="input-group-addon" id="basic-addon4">Start Time </span> <timepicker [(ngModel)]="mytime" required></timepicker></di ...

Exploring the use of Rails and jQuery to automatically update data through the use of setTimeout and ajax calls

There's a specific page accessible in the browser at "/calendar" that directs to "calendar#index". Utilizing a javascript setTimeout function, I'm attempting to re-fetch and update data on my page using $.get ajax method. $.get("<%= calendar ...

The Datepicker and Tablesorter dilemma

Having a Datepicker and Tablesorter on the same View Page presents an issue for me. When I remove the tablesorter, the datepicker functions properly. However, when I reintroduce the tablesorter, the datepicker stops working entirely. Below is the code sni ...

Tips for incorporating seamless animation effects to an element with jQuery

As I work on coding the navbar for my HTML website, I'm incorporating Bootstrap for styling and using a jQuery function to change the color of the navbar dynamically. However, I want to ensure that the color transitions smoothly when it changes. How c ...

Having difficulties creating an HTML SVG Welcome screen

I'm currently working on developing an engaging splash screen for my mobile application. To accomplish this, I need to utilize SVG, HTML, and CSS in order to align with the app's architecture. The initial GIF represents the desired outcome that ...

Styling a table in CSS to have top and bottom borders

<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <style type="text/css"> li { display:inline; list-style-type:none; padding-left:1em; margin-left:1em; border-left:1 ...

Is there a way to access fields from an associated model within React components?

Is there a way to access fields from an associated model in React components within Rails? I have a listing model that I'm iterating through in a React component and retrieving all the fields for each record, including the ID of the associated model. ...

Using the 'gf' command in Vim to resolve JavaScript modules with a Webpack tilde alias

Recently, I joined a Vue.js project that makes use of the tilde (~) notation in module imports. For example: import WhateverApi from '~/api/whatever'; The project repository is a mix of various files including a Vagrant machine setup, a Laravel ...

Is it possible to change a Material UI style without resorting to an HOC?

Is there any method to modify the styling of a Material UI component without the need to create an entirely new component using withStyles()? For example, if I am currently displaying the following and simply want to adjust the color of the "Delete" label ...

Header contains problem with cross-domain access in $http

Sending a request through Angularjs $http with JSON data to my REST service requires setting headers once the response is returned. The necessary headers are added as follows, Response.ok() .entity(emp) .headers.add("Access-Control-Allow-Origin", "*") .he ...

Align and resize image using CSS styling

Seeking assistance on centering and cropping images using CSS. Tried implementing the technique from this specific article. However, experiencing inconsistencies in device UI output. Can someone shed light on this behavior? Scenario: The objective is t ...

modifying prop values with Vue.js method

I'm currently diving into Vue and tackling a project that heavily relies on vue.js. My goal is to display data in a component using a prop, and now I'm looking to implement a method to increment the quantity of a product. Below is my code snippe ...

Resetting CSS animations using animation-delay

My aim is to animate a series of images on my landing page using Next.js and SCSS. The issue arises when I try to add dynamic animations that reset after each cycle. The delay in the animation causes the reset to also be delayed, which disrupts the flow. I ...

The Angular Http Interceptor is failing to trigger a new request after refreshing the token

In my project, I implemented an HTTP interceptor that manages access token refreshing. If a user's access token expires and the request receives a 401 error, this function is designed to handle the situation by refreshing the token and re-executing ...

Retrieving data from a script within a React component

How can I access a variable from a script inside a React component? I am performing device detection on Node and sending the resulting object to the client (React) within index.ejs. <script type="text/javascript">window.deviceType = <%- deviceT ...

Unable to interpret JSON data using jQuery's parseJSON function

Currently, I am attempting to execute server operations using AJAX jQuery(document).on('click','a.edit', function (e) { var id=$(this).prop('id'); var params="id="+id; $.ajax({ ...

What is the best way to incorporate a logo into the top left corner of the Navigation Bar?

Currently, the Studio Ghibli Logo image is embedded in the HTML code at line 17. I am looking to place it in the top left corner of the navbar. How can I achieve this? Here is a reference image: ref image If there is a more efficient way to code the navba ...

Inserting a multidimensional array into a JSON structure

Currently, I am working on populating my mongodb database with data that needs to be in a specific format. var location1 = [2,3]; var location2 = []; location2.push(location1); location2.push(location1); var location3 = []; location3.push(location2); cons ...

Explore the associative array within a JSON using jQuery to extract and manipulate the values within the array

I'm working with a JSON file containing surnames and first names in an array, along with other objects. How can I specifically extract the names "Jhon" and "Jason"? Below is a snippet from my JSON file: [{ "surname": "Vlad", "first_name": [ ...