When I add some elements to my scrollable list with jQuery's prepend()
function and I'm initially at the top of the list, the list automatically scrolls to the top of the first added element and doesn't keep the position. How can I prevent this?
This is my code example showing my problem:
jQuery(document).ready(function($) {
$("button").click(function() {
[1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(function() {
$("div").prepend("<span class='new'></span>");
});
});
});
div {
border: 1px solid;
width: 200px;
height: 350px;
overflow-y: scroll;
overflow-x: hidden;
}
span {
height: 40px;
width: 200px;
display: block;
background: gray;
}
span.new {
background: red !important;
}
span:nth-child(odd) {
background: lightgray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<button>Prepend elements</button>