Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to li element in a ul list

I have a ul list inside a div with li elements and inside the li elements is a single checkbox. I have the id for the checkboxes. So I want to get the parent li element of the checkbox and scroll to it's position. And I can't make it work.

My html is like this:

<div id="divElement">
   <ul>
      <li>
         <input type="checkbox" id="343532532523" />
      </li>
   </ul>
</div>

I tried these two methods and they don't work for me:

$('#divElement').scrollTop($('#343532532523').parent().position().top);
$('#divElement').firstChild().scrollTop($('#343532532523).parent().position().top);
like image 549
kyleb Avatar asked Oct 12 '12 18:10

kyleb


People also ask

How do I scroll a specific element?

The scroll method: The scroll() is used to scroll to the specified element in the browser. Syntax: Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. Example: Using scroll() to scroll to an element.

How do you scroll an element in HTML?

The scrollIntoView() method scrolls an element into the visible area of the browser window.

What is $( window scrollTop ()?

scrollTop property gets or sets the number of pixels that an element's content is scrolled vertically. An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. When an element's content does not generate a vertical scrollbar, then its scrollTop value is 0 .


2 Answers

If anyone needs a vanilla JS version, the following is working well for me, the value of 50 is just so that I'm showing the whole item when I'm near the top of the list. You can adjust that.

function updateListSelection(liID) {

    var list = document.getElementById("id Tag Of The <UL> element"),
        targetLi = document.getElementById(liID); // id tag of the <li> element

    list.scrollTop = (targetLi.offsetTop - 50);
};
like image 91
Darren Avatar answered Sep 22 '22 19:09

Darren


I had another dev friend of mine help me and we came up with this and it works, no animate, I could do it I just don't need it..

var offset = $('#someDivElementId ul li').first().position().top;
$('#someDivElementId').scrollTop($('#23532532532532').parent().position().top - offset);
like image 43
kyleb Avatar answered Sep 20 '22 19:09

kyleb