简体   繁体   中英

Keep DIV scrolled to bottom when new content is added

I have a page that adds a new form to the bottom of a list of forms when the previous one was submitted and although I would like the page to scroll when it reaches a certain height so it scrolls to the top hiding the oldest form and revealing the new one at the bottom.

The new forms are creating using AJAX and that part works ok, it's just the scrolling bit I can't get working.

<div id="no_image_audit_wrapper" class="content_wrapper">
<ul id="responds">
<?php

$sql = "SELECT * FROM add_delete_record";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));

//get all records from add_delete_record table
while($row = mysqli_fetch_array($result))
{ ?>
  <li id="item_<? echo $row['id'];?>">
  <div class="del_wrapper"><a href="#" class="del_button" id="del-<? echo $row['id']; ?>">
  <img src="images/icon_del.gif" border="0" />
  </a></div>
  <? echo $row["content"].' - '.$row["dropdown"].'</li>';
 }

?>
</ul>

    <div class="form_style">
    <form id="test_form">
    <select id="test" name="test">
        <option value="test1">test1</option>
        <option value="test2">test2</option>
    </select>
    <textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea>
    <input type="button" class="FormSubmit" name="FormSubmit" id="FormSubmit" value="submit">
    </form>
    </div>
</div>



<script>
  $(document).ready(function(){
    var $cont = $('.content_wrapper');
    $cont[0].scrollTop = $cont[0].scrollHeight;

    $('.FormSubmit').keyup(function(e){
    if(e.keycode == 6){
        $cont.animate({ scrollTop: $cont[0].scrollHeight }, "slow");
        $(this).val('');
          }
     })
  }
</script>

Use the below code to scroll to bottom. You can animate to scroll slowly

Javascript

window.scrollTo(0,document.body.scrollHeight);

JQuery

$('html, body').animate({scrollTop:$(document).height()}, 'slow');

Try something like this

Your_newly_added_form.scrollIntoView(true);

Or you can create a function like this

function scroll(elm){
elm.scrollIntoView(true);
}

and call that function after the completion of ajax call.

I sorted it by adding

$("#test_form").get(0).scrollIntoView();

into the success function

success:function(response){
    $("#responds").append(response);
    $("#contentText").val(''); //empty text field on successful
    $("#test_form").get(0).scrollIntoView();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM