Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Div scroll to the bottom

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);
like image 305
MVC newbie Avatar asked Mar 01 '17 09:03

MVC newbie


2 Answers

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()

like image 186
Andrii Verbytskyi Avatar answered Sep 19 '22 00:09

Andrii Verbytskyi


This worked for me:

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

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

like image 40
Katie Avatar answered Sep 18 '22 00:09

Katie