Eddie Dane
Eddie Dane

Reputation: 1569

Scrolling window to the bottom of an element

I am trying to add a functionality to a module in the application am working on, which will scroll the browser window to the bottom of an element when the element height is greater than the window's height.

the module is kinda similar to the snippet below, when you add an item to the list when the list's height is greater than the window's height you would have to scroll down to see the add button again, so is there a way i can do this automatically, by the way == (BTW) i don't mean scrolling to the bottom of the document, just a specific element.

(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>

Upvotes: 0

Views: 1383

Answers (1)

Michael Coker
Michael Coker

Reputation: 53674

This jQuery code will scroll to put the bottom of the element at the bottom of the window. I basically just get the top position of the element to scroll to, then add the height of the element to the top position to determine the bottom position. Subtracting the window height from the bottom position value, then scrolling to the resulting value will put the bottom of the element at the bottom of the window. If you want the bottom of the element to be at the top of the window (truly scrolling to the bottom of the element, but it will be out of the viewport), just scroll to 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>

Upvotes: 1

Related Questions