Prevent automatic scrolling by clicking when you reach the bottom

In order to replicate the issue I am experiencing, please click on the down button four times, and then click on the up button. You will observe that you need to click the up button one extra time for it to function properly. How can I detect when it has reached the bottom and return false?

var scrollValue = 0;
$('#down').click(function(){
      scrollValue = scrollValue + 180;
    $('ul').animate({scrollTop:scrollValue});
});

$('#up').click(function(){
      scrollValue = scrollValue + -180;
    $('ul').animate({scrollTop:scrollValue});
});
ul {
  padding: 0;
  margin: 0;
  height: 180px;
  overflow: auto;
}
li {
  height: 50px;
  background: pink;
  list-style: none;
  margin-bottom: 10px;
  height: 50px;
}
body {
  padding: 0;
  margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
</ul>
<button id="up">up</button>
<button id="down">down</button>

Answer №1

To achieve the desired behavior, it is essential to consider the container height using 'scrollHeight'. If the scroll position exceeds the height or tries to go below 0, it should be adjusted accordingly.

var scrollValue = 0;
var nHeight = $('ul').height();
var height = $('ul').prop('scrollHeight');
height = height - nHeight;

$('#down').click(function(){
      var nScrollValue = scrollValue + 180;
      if(nScrollValue < height){
         scrollValue = nScrollValue;
      } else {
         scrollValue = height;
      }
      $('ul').animate({scrollTop:scrollValue});
});

$('#up').click(function(){
      var nScrollValue = scrollValue - 180;
      if(nScrollValue > 0){
        scrollValue = nScrollValue;
      } else {
        scrollValue = 0;
      }
      $('ul').animate({scrollTop:scrollValue});
});

I recommend utilizing jQuery to facilitate scrolling actions without manually tracking 'scrollValue':

$('#down').click(function(){
      $('ul').animate({scrollTop: '+=180'});
});

$('#up').click(function(){
      $('ul').animate({scrollTop: '-=180'})
});

Answer №2

Give this a shot:

$(document).ready(function() {
    var scrollAmount = 0;
    numCases = ($("li").length/3)-1; // 3 represents the number of visible rows
    $('#down').click(function(){
        if(scrollAmount <= (numCases*180)  ){
            scrollAmount = scrollAmount + 180;
            console.log(scrollAmount)
            $('ul').animate({scrollTop:scrollAmount});
        }
    });

    $('#up').click(function(){
        if(scrollAmount >= (180)  ){
            scrollAmount = scrollAmount + -180;
            $('ul').animate({scrollTop:scrollAmount});
        }
    });
})
ul {
  padding: 0;
  margin: 0;
  height: 180px;
  overflow: auto;
}
li {
  height: 50px;
  background: pink;
  list-style: none;
  margin-bottom: 10px;
  height: 50px;
}
body {
  padding: 0;
  margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
</ul>
<button id="up">up</button>
<button id="down">down</button>

Answer №3

One way to determine the height of the document before animating the page scroll is by comparing it with the current scroll position

var documentHeight = $(document).height();

This will give you the total height of your document. If the animation occurs within a specific element, simply replace $(document) with that element

To check if the scroll has reached the bottom, use the following code snippet

if(scrollValue + 180 > documentHeight) {
    // At the bottom
}

Answer №4

Prior to adjusting your scrollValue variable by adding or subtracting 180, it is important to verify if it is already at the edge.

Here is the JavaScript code snippet:

var scrollValue = 0;
$('#down').click(function(){
      if (scrollValue < $(ul).height() ) {
          scrollValue = scrollValue + 180;
          $('ul').animate({scrollTop:scrollValue});
      }
});

$('#up').click(function(){
      if (scrollValue > 0) {
          scrollValue = scrollValue - 180;
          $('ul').animate({scrollTop:scrollValue});
      }
});

While I'm not entirely certain if the comparisons are accurate, perhaps comparing to a value other than $(ul).height() could be more appropriate. Nonetheless, this approach seems to be on the right track.

Answer №5

Make sure to check if the scrollValue is equal to or greater than 0 for it to function properly. Refer to the snippet below.

var scrollValue = 0;
$('#down').click(function(){
      if(scrollValue >= 0){
         scrollValue = scrollValue + 180;
      }
    $('ul').animate({scrollTop:scrollValue});
});

$('#up').click(function(){
    scrollValue = scrollValue + -180;
    $('ul').animate({scrollTop:scrollValue});
});
ul {
  padding: 0;
  margin: 0;
  height: 180px;
  overflow: auto;
}
li {
  height: 50px;
  background: pink;
  list-style: none;
  margin-bottom: 10px;
  height: 50px;
}
body {
  padding: 0;
  margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
</ul>
<button id="up">up</button>
<button id="down">down</button>

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

Loss of Image Quality when Zooming out Canvas

I have developed a code to implement zoom-in and zoom-out functionality for a canvas image. However, I am facing an issue where the quality of the image deteriorates when zoomed more than once. I am using the canvas2image plugin to convert the canvas into ...

Unable to retrieve information from localhost site using the expressjs API. I have attempted to use both vue-resource and axios in order to get the data without success

Currently diving into the world of VueJS, I decided to embark on a project. My aim is to retrieve data from an ExpressJS server/API. But unfortunately, both vue-resource and axios have been returning status code 0. It seems like my API might not be handli ...

Retrieve the most recent information from the API using axios and React hooks

I have access to an API that provides data, but I am only interested in the most recent information. The newest data is always located at the end of the dataset. For instance, if there are 50 points of data, the latest would be number 50. Can someone adv ...

The content inside an HTML element and covertly deciphered quotations

SETTING THE SCENE: Hidden within the page lies a perfectly structured JSON object, wrapped in a div. Within this object are HTML values encoded with double-quotes, creating a unique challenge: "additionalInfo": "If you need more help, please visit &l ...

Tips for eliminating the PHP form redirection issue

Having trouble with data insertion in MySQL and getting redirected to the PHP file after. Not ideal! Any suggestions on how I can display error or success messages within the same HTML file? index.html <form id="form" action="add_article.php" method=" ...

Excessive recursion in MooTools causing issues with Google Maps integration

Hello, I'm currently facing an issue with my WordPress plugin. Whenever Mootools is included, Google Maps are not displaying due to "too much recursion" error. Here is a snippet of the code for reference: Any suggestions or workarounds for this incon ...

Selenium can locate an element by its CSS selector that comes after a specific element

How can I locate the text "Interesting" which is the first occurrence of the class b after h1.important when using Selenium? <div class="a"> <div class="b">Not interesting</div> </div> <div class="title"> <h1 c ...

Guide to initiating a node.js socket.io server through a brackets extension

I am currently working on developing a brackets extension that involves sending data to a server. What I aim to do is execute a server.js file from my main.js file, which will create a node.js socket.io server. Once this server is set up, the extension sho ...

Utilizing optional parameters with React Router

Imagine I have a page at http://www.example.com/page/#/search set up with the following routing: <Router history={hashHistory}> <Route path='/search/' component={SearchPage} /> </Router> When a user performs a search using t ...

Jumpstarting jQuery's constructor

Is there a way to modify jQuery's constructor in order to add additional functionality before its default behavior kicks in? For example, let's say we want to enable automatic caching... Pseudo-code ahead! var _init = $.fn.init; var cache = [] ...

Tips for achieving vertically centralized components with uniform height columns in Bootstrap 4

I tried implementing the solution provided in this question: Bootstrap 4 vertical center - equal height cards However, I am still facing an issue. Despite applying the suggested code: <div class="cycle-des h-100 justify-content-center">Product Cycl ...

Utilizing Jquery tabs for consistent height display

Currently, I am utilizing jquery tabs for showcasing various content. This is what my functions look like: $(function() { $( "#tabs" ).tabs(); }); I attempted to ensure all tabs have the same height by using this approach: var heightStyle = ...

pop-up window that shows chosen choices using javascript or ajax

I have a specific HTML code that allows users to select multiple options. I would like these selected options to be displayed in a popup or a div in real-time as the user makes their selections. I have attempted using a selectbox with checkboxes, but extra ...

Partial display issue with SweetAlert popup

I am currently working on a personal project using ASP.NET MVC5 and incorporating SweetAlert for managing message alerts. However, I have encountered an issue where the alert message only appears for a brief moment when testing it on an HTML5 button with t ...

Having trouble with jqGrid data format?

Having some trouble with jqGrid and displaying data in a treeview format. The issue is that the 6th item (cid=6) is not appearing in the grid. Additionally, it seems like the 4th item may have subitems, but expanding that branch reveals nothing. I cannot f ...

Increasing the size of a card beyond the container using the CSS PRE tag

I am facing an issue with a card on my webpage. It contains a pre tag inside it, which is causing the size of the card to extend beyond its container, resulting in a horizontal scroll bar appearing. How can I make the content within the pre tag scroll hori ...

Switching Languages in react-simple-keyboard: Explained

import React, { useRef, useState } from "react"; import Keyboard from "react-simple-keyboard"; import "react-simple-keyboard/build/css/index.css"; function App() { const [input, setInput] = useState(""); const [ ...

Is there a way to sort through objects in a JSON file using two shared values? Specifically, I'm looking to filter the JSON objects based on both common x and y values

Given a JSON file, I am looking to group objects based on common x and y values. Essentially, I want to group together objects that share the same x and y properties. Here is an example of the JSON data: let data = [{ "x": "0", "y& ...

What is the proper way to ensure a flex item takes up 50% of the space when a gap is included in

It appears that I have misunderstood something about flexbox and am struggling to resolve the issue correctly. In my current setup, I have a flexbox container with four columns as its direct children. I want each .flexbox-item to take up 50% of the contai ...

Bringing a JavaScript function into a TypeScript file results in it being treated as a namespace

Trying to bring a vanilla JavaScript function into a TypeScript file within a React Native app has presented some challenges. The import process goes smoothly when working with JS, but switching to TS triggers the error message: Cannot use namespace &apos ...