Is it possible to place the focus point on the page, so if the content changes, the scroll bar moves with that point?

My question is pretty much the name, I have a bulletin board that constantly expands and pushes messages when new ones are added. For example, I want to block scrolling to a message so that the scroll bar of the page moves when the bulletin board expands to keep the same kind of messages that were originally. Is this possible with jquery? Any advice is appreciated.

+3
source share
2 answers

You will need to register a callback or event handler that fires every time the content on the page changes.

. http://demos.flesler.com/jquery/scrollTo/.

...
// Insert this code where you are adding the message to the page
// New message, trigger the custom event callback
// Assumes 'message' is a jQuery object for the new message.
message.trigger('scroll-to-message');
...

jQuery(function() {
  // Bind a handler for all messages (which should have a class 'message')
  // with a custom event name
  jQuery(document).delegate('.message', 'scroll-to-message', function() {
    var message = jQuery(this);
    jQuery.scrollTo(message);
  });
});
+1

, . " ", " ".

.

HTML

:

<div id="board">
    <span class="message" order="2">Message Foo</span>
    <span class="message" order="3">Message Bar</span>
    <span class="message" order="1">Message Test</span>
</div>

JS

$(document).ready(function(){   
    // each half second, updates scroll
    window.setInterval(updateScroll, 100);    

    // after 2 seconds, add new message to test scroll
    window.setInterval(newMessage, 2000);             
});

// find message with bigger order number, and scroll to it
function updateScroll(){
    var messages = $(".message");
    var newMessage = $(messages[0]);
    $(".message").each(function(){
        if ($(this).attr("order") > $(newMessage).attr("order")) {
            newMessage = $(this);
        }
    });
    var top = newMessage.offset().top;
    $(document).scrollTop(top);    
}

function newMessage() {
    var text = Date() + "<br/> - new message!";
    var tag = "<span order=\"9\" class=\"message\">" + text + "</span>";
    $('#board').prepend(tag);
}

jsfiddle


:

  • $(document).ready:
  • window.setInterval(updateScroll, 100);: updateScroll 0,1 .
  • $(".message").each(function(){...}):
  • $(document).scrollTop(top):
+1

Source: https://habr.com/ru/post/1765424/


All Articles