How to scroll to an element of html using Jquery?

Dung Do Tien Apr 10 2020 431

I have a table content and I want to click on items that will scroll to the corresponding content.

<div class="col-md-2">
    <div class="table-content">
      <ul class="item-index">
            <li data-item="1">1. Heading 1</li>
            <li data-item="2">2. Heading 2</li>
            <li data-item="3">3. Heading 3</li>
            <li data-item="4">4. Heading 4</li>
         </ul>
    </div>
    <div class="content-articles">
         <h1>Heading of article</h1>
         <p>Sapo of article</p>
         <h2 data-item="item1">Content Heading 1</h2>
         <h2 data-item="item2">Content Heading 2</h2>
         <h2 data-item="item3">Content Heading 3</h2>
         <h2 data-item="item4">Content Heading 4</h2>
    </div>
</div>
$(".table-content ul.item-index li").click(function(){
   // How can i scroll to the corresponding content here? 
});

How to achieve it? Thanks in advance.

Have 1 answer(s) found.
  • S

    Sandeep Kumar Apr 12 2020

    In this case:

    1. To scroll to any element you have two ways.

      + Use scrollTop() function

    $(window).scrollTop(200); 
    

      + Use scrollTop property with animate() method

    $('html,body').animate({
    	scrollTop: "200px" // scroll down 200px of document
    }, 'slow'); 
    

    You should use the animate() method because it supports effect smooth more than.

    2. To get the position of an element use offset() method and top property

    example get the position of first <h2> in your demo

    var position = $(".content-articles").offset().top;
    // return head position of that tag 

    Summary: Combine the two functions above to solve your problem with some lines of code as below:

    $(".table-content ul.item-index li").click(function(){
      var toElm = "item" + $(this).data("item");
      var position = $(".content-articles h2[data-item='"+ toElm +"']").offset().top;
      $('html,body').animate({
    	  scrollTop: position + "px" 
      }, 'slow'); 
    }); 

    You can refer my demo code here

    I hope this helpful to you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close