Scroll into view
Determine if the element is in view if not bring it using scrollIntoView API
by Dipak1991
HTML
<ul>
<li id='1'>element 0</li>
<li id='2'>element 1</li>
<li id='3'>element 2</li>
</ul>
Visible elements:
<span id="visible-items"></span>
<br/>
Invisible elements:
<span id="invisible-items"></span>
CSS
ul {
height:130px;
border:1px solid black;
overflow:scroll;
}
li {
height:200px;
margin:0;
border:1px solid black;
}
JavaScript
$('ul').scroll(function() {
var $ul = $(this);
$('#visible-items').html( '' );
$('#invisible-items').html( '' );
$ul.find('li').each( function (n) {
var $this = $(this);
if ( $this.position().top + $this.height() > 0 && $this.position().top < $ul.height() ) {
$('#visible-items').html( $('#visible-items').html() + ', ' + n );
} else {
$('#invisible-items').html( $('#invisible-items').html() + ', ' + n );
console.log("not visible - " + this.id);
}
});
});
$('#2')[0].scrollIntoView({ block: "end", behavior: "smooth" });