So, as I said in my comment. You need the height of the container (s scrollHeight
), and if the scroll goes further, it should be equal to the height. Same thing when it tries to go below 0. It should reset to 0.
var scrollValue = 0;
var nHeight = $('ul').height();
var height = $('ul').prop('scrollHeight');
height = height - nHeight;
$('#down').click(function(){
var nScrollValue = scrollValue + 180;
if(nScrollValue < height){
scrollValue = nScrollValue;
} else {
scrollValue = height;
}
$('ul').animate({scrollTop:scrollValue});
});
$('#up').click(function(){
var nScrollValue = scrollValue - 180;
if(nScrollValue > 0){
scrollValue = nScrollValue;
} else {
scrollValue = 0;
}
$('ul').animate({scrollTop:scrollValue});
});
var scrollValue = 0;
var nHeight = $('ul').height();
var height = $('ul').prop('scrollHeight');
height = height - nHeight;
$('#down').click(function(){
var nScrollValue = scrollValue + 180;
if(nScrollValue < height){
scrollValue = nScrollValue;
} else {
scrollValue = height;
}
$('ul').animate({scrollTop:scrollValue});
});
$('#up').click(function(){
var nScrollValue = scrollValue - 180;
if(nScrollValue > 0){
scrollValue = nScrollValue;
} else {
scrollValue = 0;
}
$('ul').animate({scrollTop:scrollValue});
});
ul {
padding: 0;
margin: 0;
height: 180px;
overflow: auto;
}
li {
height: 50px;
background: pink;
list-style: none;
margin-bottom: 10px;
height: 50px;
}
body {
padding: 0;
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
<button id="up">up</button>
<button id="down">down</button>
Run codeHide resultI think you should let the browser do this for you, no need to track on scrollValue
:
$('#down').click(function(){
$('ul').animate({scrollTop: '+=180'});
});
$('#up').click(function(){
$('ul').animate({scrollTop: '-=180'})
});
$('#down').click(function(){
$('ul').animate({scrollTop: '+=180'});
});
$('#up').click(function(){
$('ul').animate({scrollTop: '-=180'})
});
ul {
padding: 0;
margin: 0;
height: 180px;
overflow: auto;
}
li {
height: 50px;
background: pink;
list-style: none;
margin-bottom: 10px;
height: 50px;
}
body {
padding: 0;
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
<button id="up">up</button>
<button id="down">down</button>
Run codeHide result