Laila Laila - 2 months ago 7
jQuery Question

Automatic Horizontal scroll in Div element in HTML

I have a div html element in my view that contains a 3 sub div elements inside it, and i had designed it to display the sub div elements on the same line (beside each other not under each other) , each sub div element contains some control and each sub div element has a fixed width .

I want to set a button in the page that when user clicks on that button it triggers the horizontal scroll of the main div element and scroll it into certain position.

How should i do this ? . it is better if it could be done using Javascript or Jquery but if there is any other solution it would be Okay.

if there is anything in the question that needs clarification , just tell me.



<!DOCTYPE html>
<html>

<head>
<style type="text/css">
.container div {
width: 20%;
height: 200px;
background: red;
float: left;
}
#two {
background: yellow;
}
#three {
background: violet;
}
.container {
height: 100%;
width: 4000px;
}
#button-container {
position: fixed;
bottom: 20px;
left: 40px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
$('body').on('click', 'button', function () {
var target = '#' + this.id.split('-')[1]
var offsetLeft = $(target).offset().left
$('body').animate({
scrollLeft: offsetLeft
}, '500');
})

</script>
<title></title>
<meta charset="utf-8" />



</head>
<body>

<div class="container">
<div id="one">hello</div>
<div id="two">hello</div>
<div id="three">hello</div>
</div>

<div id="button-container">
<button id="scroll-one">Scroll to div 1</button>
<button id="scroll-two">Scroll to div 2</button>
<button id="scroll-three">Scroll to div 3</button>
</div>

</body>
</html>




Answer

Try this.

Use scrollLeft() to scroll horizontally. Hope it helps

$('body').on('click', 'button', function() {
  var target = '#' + this.id.split('-')[1]
  var offsetLeft = $(target).offset().left
  $('body').animate({
    scrollLeft: offsetLeft
  }, '500');
})
.container div {
  width: 20%;
  height: 200px;
  background: red;
  float: left;
}
#two {
  background: yellow;
}
#three {
  background: violet;
}
.container {
  height: 100%;
  width: 4000px;
}
#button-container {
  position: fixed;
  bottom: 20px;
  left: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div id="one">hello</div>
  <div id="two">hello</div>
  <div id="three">hello</div>
</div>

<div id="button-container">
  <button id="scroll-one">Scroll to div 1</button>
  <button id="scroll-two">Scroll to div 2</button>
  <button id="scroll-three">Scroll to div 3</button>
</div>