Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

304
Views
Scrolling to the child element of a scrollable parent

I have a scrollable ul, and several li-items. My goal is to scroll to the li-item with certain id when the user presses a button.

I have a code which seems to work, but there are two issues

  1. If I scroll down to the end of the list as page loads, the button does not work anymore. Comment out and uncomment the line as mentioned in the code to see what I mean
  2. If I am already on the wanted item in the list, I want to stay on the same place if I press the scroll-button.

I guess, both issues are because of some relative coordinates, but I can't figure out how this system works. Help me please!

HTML:

<ul id="container">
  <li id="1">stuff1</li>
  <li id="2">stuff2</li>
  <li id="3">stuff3</li>
  <li id="4">stuff4</li>
  <li id="5">stuff5</li>
  <li id="6">stuff6</li>
  <li id="7">stuff7</li>
  <li id="8">stuff8</li>
  <li id="9">stuff9</li>
  <li id="10">stuff10</li>
  <li id="11">stuff11</li>
  <li id="12">stuff12</li>
  <li id="13">stuff13</li>
  <li id="14">stuff14</li>
  <li id="15">stuff15</li>
  <li id="16">stuff16</li>
</ul>
<button id = 'btn'>Scroll to element with id = 9</button>

JS:

var $container = $('#container')[0];

// $container.scrollTop = $container.scrollHeight;
// If I uncomment the above line, the code does not work any more
$('#btn').click(function(){
     $container.scrollTop =  $('#9').position().top;
});

CSS:

ul {
  overflow-y: auto;
  position: relative;
  height: 300px;
  width: 300px;
  background: red;
}

ul li {
  margin: 30px;
  border: solid;
}

See the JSFiddle

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

The 9 element will be positioned relative to the scroll too. You have to append the current scroll to the 9 position, like this: http://jsfiddle.net/rck1ow93/2/

$container.scrollTop = $container.scrollTop+$('#9').position().top;
about 4 years ago · Santiago Trujillo Report

0

To add to Jorge's answer, in addition to taking scroll into account, you might want to use .offset() instead of .position(), as it will give you the correct position. So change

$container.scrollTop =  $('#9').position().top;

to

$container.scrollTop += $('#9').offset().top;

http://jsfiddle.net/t06fjtqd/

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!