Navigating to the bottom of a specific element by scrolling

I am currently working on enhancing a module within the application I'm developing. The goal is to automatically scroll the browser window to the bottom of an element when said element's height exceeds the height of the window.

The functionality is similar to the example snippet below - in this scenario, adding an item to a list that surpasses the window's height requires manual scrolling to view the add button again. Is there a way to automate this process specifically for a designated element, without having to scroll to the bottom of the entire document?

(function() {

  var lists = document.querySelector('ul'),
    addBtn = lists.nextElementSibling.lastElementChild,
    textInput = addBtn.previousElementSibling;

  addBtn.addEventListener('click', appendItem);

  function appendItem() {
    var item = document.createElement('li');
    if (textInput.value == '') item.innerText = 'test-item';
    else item.innerText = textInput.value;

    lists.appendChild(item);
  }

  console.log(lists, addBtn, textInput);
})();
div:not(#fake-form) {
  background-color: #F9F2C4;
  max-width: 200px;
  margin: 0 auto;
}
ul {
  list-style: none;
  padding: 4px;
  margin: 0;
}
ul li {
  list-style: none;
  padding: 4px;
  margin: 0;
  font-size: 24px;
}
div#fake-form {
  text-align: center;
  padding: 4px;
}
input {
  display: block;
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 4px;
}
<div>
  <ul>
    <li>test item</li>
    <li>test item</li>
    <li>test item</li>
    <li>test item</li>
    <li>test item</li>
    <li>test item</li>
    <li>test item</li>
  </ul>
  <div id="fake-form">
    <input type="text">
    <button>add item</button>
  </div>
<div>

Answer №1

This JavaScript snippet is designed to scroll a specific element such that its bottom aligns with the bottom of the window. By calculating the top position of the element and adding its height, the script can determine the bottom position. Then it subtracts the window's height from this value to find the correct scroll position. If you prefer the element's bottom to align with the top of the window (even if it goes out of view), just scroll to the divBot instead.

$('button').on('click', function() {
  var wHeight = $(window).height(),
    divTop = $('#one').offset().top,
    divHeight = $('#one').outerHeight(),
    divBot = divTop + divHeight;
  
  $('html, body').animate({
    scrollTop: (divBot - wHeight)
  }, 2000);
})
div {
  height: 200vh;
  border-bottom: 5px solid black;
}
#one {
  border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><button>click</button></div>
<div id="one"></div>
<div></div>

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

issue with arranging content in a two-column layout with headers

Currently working on my first website and running into some CSS issues. I'm aiming for a two-column + header layout that fills the entire screen space of the website. I have the following specifications in mind: Header takes up 20% of the screen he ...

Issue with Vue JS component on blade template page

Having trouble loading a Vue component into a Laravel blade file? Despite making changes, the content of my vue file isn't showing up in the blade file - even though there are no errors in the console. Any suggestions on how to resolve this issue woul ...

A common inquiry: how can one pinpoint a location within an irregular figure?

I have been studying Html5 Canvas for a few weeks now, and the challenge mentioned above has puzzled me for quite some time. An irregular shape could be a circle, rectangle, ellipse, polygon, or a path constructed by various lines and bezier curves... I ...

Troubleshooting HTML image visibility issues

I've been trying to get a Tumblr icon to display in the upper-right corner of my HTML-based page, but all I see when I open it in a browser is a white box with a gray outline. The code I'm using for the image is: <img style="float: right; mar ...

Enhance your textbox with more detailed descriptions than just displaying NaN

I am working on a form that includes select boxes. If a user selects an option from "Convert From" and another option from "Convert To" but does not enter a number in the input field, instead of displaying NaN in the result text box, I would like to show ...

Vue.js encountered an error: Unexpected TypeError in promise. The function $set is not recognized

Currently, I am working on fetching comments from the Reddit API and attempting to update an array using $set in order to refresh the view. However, I encountered an error: Uncaught (in promise) TypeError: $set is not a function Virtual Machine Component ...

"Server request with ajax did not yield a response in JSON format

http://jsfiddle.net/0cp2v9od/ Can anyone help me figure out what's wrong with my code? I'm unable to see my data in console.log, even though the network tab in Chrome shows that my data has been successfully retrieved. Here is my code snippet: ...

Placing information within a nested array with multiple levels of nesting

I'll try to keep this concise, Here is the structure of the schema... import mongoose from 'mongoose' const QuestionSchema = mongoose.Schema({ questionTitle: { type: String, required: " title"}, questionBody: { type: Stri ...

Using Javascript, verify if a given URL is legitimate and commences with "http://" or "https://"

I need to validate the authenticity of my URLs, ensuring they begin with either http:// or https://. Here is the regular expression (RegExp) I have been using: private testIfValidURL(str) { const pattern = new RegExp('^(https?:\\/&bsol ...

Transferring information between two pages when a button is clicked in Angular

How can I display hero details on the hero-details page when clicking a button? I'm currently struggling to make it work. When I click the button, the details show up on the hero-list page, but using the routerLink doesn't display the data. I am ...

Encountering Internal Server Error when running Node-Express app on render.com with query parameters live

Currently, I am facing an issue while attempting to execute a live route with query using my nodejs express application on render.com. Strangely, all other routes connected to the crud operations are functioning properly except for the search filter route ...

Having trouble resolving row border issues with CSS in DataTables?

I need to enhance the appearance of specific rows in my table by adding a darker border at the bottom. To achieve this, I have assigned a custom class (des-rec-row) to the rows and included the following CSS code: .des-rec-row { border-bottom: 1px soli ...

Tips for obtaining accurate response from axios

When utilizing axios, I receive my query response in the format of response.data.response.object. Is there a way to access the answer directly without going through response.data first? ...

The problem with the first item title in the Jquery slider is causing

I've been working on setting up a Jquery slider (caroufredsel) in which I want certain elements to be displayed above the slider itself, outside of the wrapper. Everything is working fine except for the first slide! After spending several days trying ...

Switch between multiple unordered lists (ul) so that when one list is clicked, the other lists reset to their initial state as though they were never

When I click on the first item in the ul list, it should slideToggle() to show its corresponding items. Similarly, when I click on the second item in the ul list, its items should slideToggle(), but the first ul list remains visible as well. What I am tryi ...

Is it possible to utilize an API response within a conditional statement in NextJS?

I am working on a change password feature that interacts with an API for verification. If the current password entered is incorrect, I want to display an error message. If you have any suggestions on how to proceed or if there are any flaws in my approach ...

Building nested routes in a protected path using react-router version 6

At the moment, I am utilizing react-router-dom version 6.1.1 and I have a private route in use. Typically, within this private route, I include other routes to maintain my Sidebar. This is how my code appears: // App.tsx const RequireAuth: React.FC<P ...

Utilizing Images with 'General Drawing' in Highcharts

I'm currently attempting to create a task diagram using Highcharts. I had the idea of incorporating images using the <img> tag ren.label('<img src="/images/test.jepg', 10, 82) .attr({ ...

Elements on the left side are not properly aligned

I've successfully coded the head banner and news containers below the header. However, I'm facing an issue with my left menus: Instead of aligning properly with the header and news containers, they are overlapping them. Here is the HTML Code: ...

Having trouble with the Jquery Slider script?

I recently integrated a slider from into my website, following the installation instructions. However, I seem to be facing some conflicts with another script that controls animated div movements on the same page. Upon loading the page, all elements of th ...