Sooraj Chandran Sooraj Chandran - 4 months ago 11
jQuery Question

Scroll to a div horizontally not working

I have the following code. I'm trying to scroll to a div horizontally on click of a button.



jQuery(document).ready(function() {
jQuery("#clickme").click(function() {

jQuery("#parent").animate({
scrollLeft: jQuery("#child").position().left
}, 500);
});
});

#parent {
width: 1000px;
height: 200px;
background: #ccc;
position: relative;
}
#child {
position: absolute;
right: 200px;
height: 100px;
width: 100px;
background: blue;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<button id="clickme">
Click Me
</button>
<div id="child">
child div
</div>
</div>





There are no errors in console. What am i doing wrong ?

Answer

"It is the body you should animate because it is the one who have a scrollbar."

Your code should be right if the scenario is like this,

(Just change your CSS like this)

#parent {
  width: 350px; /* Make it shorter for scroll to work */
  height: 200px;
  background: #ccc;
  position: relative;
  overflow: scroll; /* To show scrollbar */
}
#child {
  position: absolute;
  right: -150px; /* Make it negative also to make scroll working */
  height: 100px;
  width: 100px;
  background: blue;
}

As you can see there, your code would work if it is like that..


But now, I will base on your current scenario..

From jQuery("#parent"), is should be jQuery("body")

WORKING NOW:

jQuery(document).ready(function() {
  jQuery("#clickme").click(function() {

    jQuery('body').animate({
      scrollLeft: jQuery("#child").position().left
    }, 500);
  });
});
#parent {
  width: 1000px;
  height: 200px;
  background: #ccc;
  position: relative;
}
#child {
  position: absolute;
  right: 200px;
  height: 100px;
  width: 100px;
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
  <button id="clickme">
    Click Me
  </button>
  <div id="child">
    child div
  </div>
</div>

Comments