Page 1 of 1

setInterval() issue..

Posted: Wed Aug 08, 2012 11:15 pm
by Pazuzu156
I'm using setInterval to read a log that is updated frequently. However, if I want to select the text it displays from the log, when it refreshes it, I cannot select the text because of it refreshing. So my question here would be, how do I make this load ONLY when a new entry is created?

An example:

Code: Select all

$(function() {
  function loadlog() {
        var oldscrollheight = $("#log").prop("scrollHeight") - 20;
        $.ajax({
            url: './assets/log.php',
            cache: false,
            success: function(data) {
                $("#log").html(data);
                var newscrollheight = $("#log").prop("scrollHeight") - 20;
                if(newscrollheight > oldscrollheight)
                    $("#log").animate({scrollTop: newscrollheight}, 'slow');
            }
        });
    }

    setInterval(loadlog, 100);
});

Re: setInterval() issue..

Posted: Thu Aug 09, 2012 12:05 am
by requinix
Would you rather keep the selection even after it changes? You can do that. Google around for selection ranges: something like document.createRange() and some object.getSelection() I think.

Otherwise don't .html() unless the data != the current value. Or put something in the AJAX business that keeps track of, say, last-updated timestamps, and indicates in the returned data whether the thing (timestamp) has changed.

Re: setInterval() issue..

Posted: Thu Aug 09, 2012 1:28 pm
by tr0gd0rr
What about instead of updating the entire #log element, you could insert a new <p> or <li> element? If you animate the inserted element with .slideDown(), you don't have to worry about the scroll height. Unless you are trying to put it in a textarea or something. I wouldn't put the log text in a textarea

Re: setInterval() issue..

Posted: Thu Aug 09, 2012 4:59 pm
by pickle
I'd send along a timestamp of your last poll when you call log.php. log.php can then only send you the entries that have been entered since that timestamp. Rather than using .html(), append the new entries to the #log element. Then your selection won't be affected.

Re: setInterval() issue..

Posted: Fri Aug 10, 2012 1:15 am
by Pazuzu156
The log area is a div element, not a textarea. The scrolling is for once a new entry is made to automatically scroll down and display it.