lys916 lys916 - 6 months ago 10
Javascript Question

I have a horizontal scroll with overflow hidden, how do i make it scroll to the center when i click it?

i want to make it so when i click on each number, that number will scroll to the center of the container. here's what i got so far in jsfiddle.
https://jsfiddle.net/bf3nv33d/2/

here are the codes..

html
<div id='container'>
<div id='scrollbox'>
</div>
<div id='display'>
</div>
</div>

css
#container{
border:1px solid blue;
height:200px;
width:200px;
}
#scrollbox{
height:43px;
overflow-x:scroll;
overflow-y:hidden;
white-space:nowrap;
}
.numberbox{
display: inline-block;
background-color: white;
padding: 2px 2px 2px 2px;
width:20px;
border-right:1px solid green;
}

jquery
for(var i=1; i<21; i++){
var numberbox = "<div class='numberbox numberbox"+i+"'>"+i+"</div>";
$('#scrollbox').append(numberbox);
}

$('.numberbox').on('click', function(){
$('.numberbox').css('background-color', 'white');
$(this).css('background-color', 'yellow');
$('#scrollbox').animate({
scrollLeft: $('.numberbox4').offset().left}, 200);
});

Answer

for(var i=1; i<21; i++){
var numberbox = "<div class='numberbox' id='"+i+"'>"+i+"</div>";
$('#scrollbox').append(numberbox);
}

$('.numberbox').on('click', function(){
	$('.numberbox').css('background-color', 'white');
	$(this).css('background-color', 'yellow');
  $('#scrollbox').animate({
  	scrollLeft: this.id*25-112.5}, 200);
});
#container{
  border:1px solid blue;
  height:200px;
  width:200px;
  
}
#scrollbox{
  height:43px;
  overflow-x:scroll;
  overflow-y:hidden;
  white-space:nowrap;
}
.numberbox{
  display: inline-block;
  background-color: white;
  padding: 2px 2px 2px 2px;
  width:20px;
  border-right:1px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='container'>
  <div id='scrollbox'>
  
  </div>
  <div id='display'>
  
  </div>
</div>

Is this what you are looking for? I used an id to track the box number and move to that location, plus halfway across to put it in the middle.