6

i have a textbox and a button. After pressing the add button to the table inside a div. I want the div to scroll to the bottom of the page when max-height:100px; exceededoverflow-y:auto; addbarcode(); method is a ajax post which will call a jquery dataTable methodto populate data on the server side.

try 1

var element = document.getElementById("divcontent");

        element.scrollIntoView(false);

try 2

 var element = document.getElementById("divcontent");
                $('#divcontent').scrollTo(element.get(0).scrollHeight);

try 3

 var objDiv = document.getElementById("divcontent");
                objDiv.scrollTop = objDiv.scrollHeight;

above attempts all doesnt work.

edit

<div class="row" id="divcontent" style="max-height:100px; overflow-y:auto">

<div class="col-md-12 col-sm-12">
    <table class="table table-striped table-responsive" id="codelist">
        <thead>
            <tr>
                <th>
                    SN
                </th>
                <th>
                    Serial Number
                </th>

            </tr>
        </thead>
    </table>


</div>

Javascript

$(document).ready(function () {
    $("#scanner").on('keyup paste', function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) { //Enter keycode
            var artno = $(this).val();
            if (artno.length == 32 && ) {
                addbarcode();
                $(this).val("");

            } else {
                $(this).val("");
            }
            var element = document.getElementById("divcontent");

            element.scrollIntoView(false);
        }


    });

})

final working code added animate to allow smooth scrolling . also added timer as ajax code run faster than html render .so setting a little delay allows the javascript to capture full height.

  function divscrolldown() {
    setTimeout(function () {
        $('#divcontent').animate({
            scrollTop: $("#divcontent").offset().top
        }, 500);

    }, 200);
MVC newbie
  • 579
  • 3
  • 9
  • 26

2 Answers2

15
element.scrollIntoView(false);

If false, the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor.

MDN: Element.scrollIntoView()

Andrii Verbytskyi
  • 7,155
  • 3
  • 47
  • 38
  • 1
    thank you, Really learned. i have read more 10 question in Stack Overflow, this is the only one that use scrollintoview. thank you very much. You are so genius. – defend orca Sep 28 '20 at 13:49
  • 1
    Perfect. Spent an hour trying all other solutions. This was the only one that worked for my div! – Guy Davis May 24 '21 at 16:02
0

This worked for me:

$('#scroll').scrollTop(1000000);

There's more answers here: Scroll to bottom of div?

Katie
  • 45,622
  • 19
  • 93
  • 125