简体   繁体   中英

How can I refresh a DIV and immediately scroll to the bottom?

I'm new to jQuery and I've tried these two functions:

function RefreshDiv() {
  $('#box').load('messages.php #box');
}

var scrolled = false;

function Scroll() {
  if(!scrolled){
    var log = document.querySelector('#box');
    log.scrollTop = log.scrollHeight - log.clientHeight;
  }
}

$('#box').on('scroll', function(){
  scrolled=true;
});

So far, I've tried multiple ways to articulate this like doing a setInterval function, a complete event inside of the.load() and a.on() function but neither seem to work in conjunction with each other, but they do work separately.

I would appreciate a solution on how to use my RefreshDiv() function every five seconds and then do Scroll() every second because I want to reload a box and then immediately have it scroll down, kind of something like this?:

    setInterval(Scroll, 1000);
    setInterval(RefreshDiv, 5000);

Obviously that doesn't work but I'm clueless on how else to structure this because.load() seems to always cancel out the rest of my code.

JQuery load is asynchronous, it will load data from the url into the jQuery element and, once complete, will execute the function passed as a second parameter.

The jQuery docs have a good page on the method here

As an example, try this snippet.

 const url = 'https://jsonplaceholder.typicode.com/todos/1'; $(document).ready(() => { $('#my-button').click(() => { console.log('clicked'); $('#results').load(url, () => { console.log('Everything loaded, can do something else'); }); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="results"></div> <button id="my-button">Get stuff</button>

Keep in mind that is loading json , ideally it would request html or text.

per jQuery.load() documentation , you need to put your scrolling code inside the complete function so it gets executed after the load function has gathered and processed the data.

With this in mind, your load call would look something like:

$('#box').load('messages.php #box',function () { [code to perform the scroll]] });

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