0
ul.cars(data-ng-show="$ctrl.hasCars")
                li.skill("data-ng-repeat="car in $ctrl.cars")

How can I make my window automatically scroll to the last li when is added each time?

Isigiel
  • 307
  • 2
  • 12
Pepper 92
  • 211
  • 1
  • 11
  • NO. I don't want to use jquery – Pepper 92 Oct 13 '17 at 15:16
  • OK... still, asked and answered: https://stackoverflow.com/questions/5007530/how-do-i-scroll-to-an-element-using-javascript – random_user_name Oct 13 '17 at 15:17
  • 1
    try using `Element.scrollIntoView()` https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView it's supported by all browsers, even IE8+ – Ahmed Musallam Oct 13 '17 at 15:18
  • Possible duplicate of [How do I scroll to an element using JavaScript?](https://stackoverflow.com/questions/5007530/how-do-i-scroll-to-an-element-using-javascript) – Dave Oct 13 '17 at 15:31

1 Answers1

1

As mentioned in the comment you could use Element.scrollIntoView(), you could use :last-child selector to select the last li.

Here is an example of this in action.

var list = document.querySelector('.list');
var button = document.querySelector('.updateList');

function updateList(){
 var number = Math.round(Math.random()*100);
 var li = document.createElement('li');
 li.textContent = number;
 list.appendChild(li);
 var lastLi = document.querySelector('.list li:last-child');
 lastLi.scrollIntoView(); 
}

button.addEventListener('click', updateList);
.app{
 width: 100vw;
 height: 100vh;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<button class="updateList">Update List</button> 
<div class="app"></div> 
<ul class="list">
 <li>hello</li>
 <li>World</li>
 <li>Whats up</li>
</ul>
</body>
</html>

Here is a jsbin of the above code https://jsbin.com/beqovi/edit?html,css,output

azs06
  • 3,467
  • 2
  • 21
  • 26