Search code examples
javascriptjqueryscroll

Why can't I scroll to the correct row ID using Jquery?


I am trying to replicate the code that was shown here: How to scroll to specific item using jQuery?

When I redo it using my site layout however, it does not scroll to the correct row ID (#row_15). How can I fix this?

Website layout

<div class="page-content">
<div id='row_1' asadasda></div>
<span id='row_2'><b>This text is bold</b></span>
<p id='row_3'><i>This text is italic</i></p>
<p id='row_4'><b>This text is bold</b></p>
<p id='row_5'><i>This text is italic</i></p>
<p id='row_6'><i>This text is italic</i></p>
<p id='row_7'><i>This text is italic</i></p>
<p id='row_8'><i>This text is italic</i></p>
<p id='row_9'><i>This text is italic</i></p>
<p id='row_10'><i>This text is italic</i></p>
<p id='row_11'><i>This text is italic</i></p>
<p id='row_12'><i>This text is italic</i></p>
<p id='row_13'><i>This text is italic</i></p>
<p id='row_14'><i>This text is italic</i></p>
<span id='row_15'><b>This text is bold 15</b></span>
<p id='row_16'><i>This text is italic</i></p>
<p id='row_17'><i>This text is italic</i></p>
<p id='row_18'><i>This text is italic</i></p>
<p id='row_19'><i>This text is italic</i></p>
<p id='row_20'><i>This text is italic</i></p>
<p id='row_21'><i>This text is italic</i></p>
<p id='row_22'><i>This text is italic</i></p>
</div> 

My code

var container = $('.page-content');
    scrollTo = $('#row_15');
    container.animate({
      scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
    });

Js fiddle

https://jsfiddle.net/boratsagdiyev/c58vfzq0/13/

Thanks


Solution

  • You Should you "html, body" as container. Because you are changing the position of your "body" to the position you needed. The changes below makes it working.

    var container = $("html, body");
    scrollTo = $("#row_15");
    container.animate({
      scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
    });