Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll within an overflow hidden div to a certain currently invisible element?

I have a list of elements within a overflow hidden div. So not all elements are visible. Now, if an element gets activated, it should become visible within the div.

How do I scroll to the active element using jQuery?

It's merely a convenience that the last element has the active class. It will be toggled dynamically.

 var scrollToEl = $("div.element.active");
 console.log(zoomToEl);
 #main,
 #sidebar {
   height: 200px;
 }
 #wrapper {
   width: 190px;
   float: left;
   background: grey;
   overflow: auto;
   overflow-x: hidden;
 }
 #sidebar div.element {
   height: 150px;
   width: 150px;
   background-color: green;
   margin-bottom: 10px;
 }
 #sidebar div.element.active {
   background-color: red;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
  <div id="wrapper" class="sidebar">
    <div id="sidebar">
      <div class="element" data-slide-id="0">a
      </div>
      <div class="element" data-slide-id="1">b
      </div>
      <div class="element" data-slide-id="2">c
      </div>
      <div class="element" data-slide-id="3">d
      </div>
      <div class="element" data-slide-id="4">e
      </div>
      <div class="element" data-slide-id="5">f
      </div>
      <div class="element" data-slide-id="6">g
      </div>
      <div class="element active" data-slide-id="7">h
      </div>
    </div>
  </div>
</div>

The element that should become visible:

var scrollToEl = $("div.element.active");
like image 704
k0pernikus Avatar asked Jul 02 '12 22:07

k0pernikus


People also ask

How do I scroll overflow hidden?

Use overflow: hidden instead. Use overflow-x : scroll and overflow-y : hidden , or overflow: scroll hidden instead. Use overflow-x : hidden and overflow-y : scroll , or overflow: hidden scroll instead. Use overflow: clip instead.

Which property can be used to set an element to show a scroll bar when the text overflows?

The overflow-x CSS property sets what shows when content overflows a block-level element's left and right edges. This may be nothing, a scroll bar, or the overflow content.

What is overflow scroll in CSS?

The overflow property specifies what should happen if content overflows an element's box. This property specifies whether to clip content or to add scrollbars when an element's content is too big to fit in a specified area. Note: The overflow property only works for block elements with a specified height.


1 Answers

You can set the scrollTop of the wrapper div to be the top of the position of the active element.

$("#wrapper").scrollTop($("#wrapper").scrollTop() + $("div.element.active").position().top);

DEMO

like image 81
sachleen Avatar answered Oct 16 '22 15:10

sachleen