Search code examples
javascripthtmlcssscroll

How to scroll to particular element using CSS/JS


This is the dummy code. My requirement is when I click on last li element then one hidden div inside it will be displayed.But I need to scroll down to it to see it. So when I click on li with id=hello then window should automatically scroll down to that div?

First preference using CSS then JS and no jQuery.

var ele=document.getElementById('hello');


ele.addEventListener("click", function (event) {
    document.getElementById("hidden-div").style.display="block";
},false);
.fixed-height-div{
 height:120px;
 overflow-y:scroll;
}

.fixed-height-div > li{
    background-color:lightblue;
    list-style-type: none;
}
<div class="fixed-height-div">
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
  <li>E</li>
  <li>F</li>
  <li>G</li>
  <li id="hello">H
      <div id="hidden-div" style="display:none;">
          This should be displayed after click<br><br>
          And the scroll should come to this screen.
       </div>
    </li>


Solution

  • Just after you show/expand your hidden div, call the scrollIntoView function of the li element.

    This requires no jQuery.

    function showIt(elementId) {
        var el = document.getElementById(elementId);
        el.scrollIntoView(true);
    }
    

    For more refer https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView