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

Using session variables on a different php page

Having trouble using a session variable in another page? I fetched data from a database and stored it in a variable, but when I attempt to use it on another page, I get an error saying 'undefined index'. See the code below - can someone help me s ...

Javascript postback functionality is fully operational in bootstrap 4, however, it is failing to return

Encountering an issue with my postback JavaScript function in the ASP/BootStrap environment. After searching on stackoverflow for a solution, I couldn't find one that resolved my problem. The problem is when I click on an image, the page reloads (the ...

Hovering does not activate the CSS dropdown

I have been struggling to implement a pure CSS menu that shows on hover. Although everything seems to work fine, I encounter an issue when trying to hide and then show the menu again upon hover. Here is the HTML code: <ul id="nav-menu"> <li& ...

Troubleshooting MongoDB aggregate lookup failure when using multiple parameters

In my data retrieval process from the comments table, everything is functioning properly. However, I am aiming to optimize performance by performing a join equivalent on the users collection to fetch additional user details associated with each comment. B ...

Display a single image on the tablet and a distinct image on the computer

Currently, I am encountering an issue with my webpage located at . The problem lies in the right upper corner where a ribbon is located. However, when viewing the page on a tablet, the ribbon overlaps with my menu. To resolve this, I thought about displa ...

How to create nested nav menus that are optimized for touch-screen devices?

When it comes to creating responsive websites, one challenge I frequently encounter is designing a multi-level nav menu that functions effectively for touch devices. Many plugins and methods exist, but most fall short because they do not allow a second-l ...

Customizing colors for the progress bar in Angular Material

In my Angular 5 project, I am using a material progress bar and hoping to customize the colors based on the percentage progress. Despite trying various methods from other sources (including previous SO questions), I have been unsuccessful in getting it to ...

"Looking to programmatically close a modal in JavaScript that was opened using the 'data-target' attribute? Here's how you can

I have a modal template embedded in the same HTML file as my controller. <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modalDeleteItem">Delete selected item</button> < ...

Tips on resolving JavaScript's failure to adjust to the latest HTML inputs

I'm working on a homepage where users can choose their preferred search engine. The issue I'm facing is that even if they switch between search engines, the result remains the same. I've experimented with if-then statements, but the selecti ...

What is the best way to create two MUI accordions stacked on top of each other to each occupy 50% of the parent container, with only their contents scrolling

I am looking to create a layout with two React MUI Accordions stacked vertically in a div. Each accordion should expand independently, taking up the available space while leaving the other's label untouched. When both are expanded, they should collect ...

Adjust the sizes of the points according to the level of zoom

I've been working on creating a dynamic map in d3.js that displays US Science funding agencies as points, with their sizes scaling based on zoom level. I referred to this starter kit for guidance. While there are other solutions out there, they often ...

Displaying Material UI Styles: A Challenge

Currently working on a website using Material-UI and React. Strangely, the styling applied through Material-UI's Hook API functions perfectly on codesandbox.io but fails to work when running locally. Notably, the border radius feature fails to update ...

Interact with an external JavaScript function using a button within a web application

I have a JavaScript file called dmreboot_service.js in my /js folder. By running this file with the command node /js/dmreboot_service.js, it successfully triggers a direct method in Azure. My goal is to be able to run this function or file when a button o ...

Integrate React tags with Redux form to ensure the values are transmitted as an array within the payload

I am currently working on a redux-form that contains a component for tags. I am struggling to figure out how to retrieve the tag values in an array as a payload. Any help would be greatly appreciated. Below is the code snippet for the tags component: ...

Shifting divs to different positions upon clicking

I am currently working on a project where I have three divs in a container positioned next to each other. My goal is to make them change their positions when clicked. For example, clicking on the left div should move it to the center position. Here is my p ...

What is the best way to move to a new line without creating a space between the current line and the new line?

I am trying to achieve the desired output: $text = Hello, this is example text. rather than: $text = Hello, this is example text. When I use \n, it starts a new line. How can I make it stay on the same line below with the same startin ...

Enriching an array with values using Mongoose

Is there a way to assign a User as an admin for the School? School Schema: const School = new Schema({ name: { type: String, required: true }, grades_primary: [{ type: Schema.Types.ObjectId, ref: 'Grade' }], grades_secondary: [{ type ...

Can Highchart dynamically adjust color choices based on the quantity of data points available?

I am trying to figure out how to import a specific color palette into my column graph. I want to use different color palettes based on the number of data points in my graph - for 3 or fewer points, I want to use the top row colors, for 4 points I want to u ...

css side by side with immovable element

Seeking assistance with CSS. I am looking to create a layout as follows: I want a center-fixed menu with a width of 960px - this part is straightforward. Alongside the menu, I aim to have two divs: one spanning from the left edge of the screen to the cl ...

Tips for accessing a file in AngularJS

Can AngularJS be used to read files? I am interested in placing the file within an HTML5 canvas for cropping purposes. I was considering implementing a directive. Below is the JavaScript code that I plan to include in my directive: function readURL(input ...