0

I'm trying to load more messages from database after I scroll to the top of the div:

$('#chatbox').on('scroll', function(){
    console.log($('#chatbox').scrollTop());
    if ($('#chatbox').scrollTop() == 0) {   
        var count = parseInt($('#chatroom-table tr').length) + 10;
        $.get('get_chatroom_messages/' + count, function(responseData) {
            $('#chatroom-div').replaceWith(responseData); 
        });
    }
});

This works great - once. After the replaceWith() is called for the first time, the scroll() method stops working. I tried rebinding the event, but with no success.

I thought that the .on method takes care of elements that are not yet created / are replaced.

EDIT:

I also tried this, but the event doesn't even fire at all then:

$('body').on('scroll', '#chatbox', function(){
    ....
});

EDIT2:

ehhh, I'm marking myself as a duplicate: Events not registering after replaceWith

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rok Dolinar
  • 976
  • 3
  • 13
  • 29
  • What does your HTML look like? Are you perchance overwriting the element the eventlistener is attached to? – Andre Nuechter Dec 09 '19 at 18:58
  • Yes, the element (#chatbox) is overwritten, but it is created again with same attributes. Does that mean that the event listener is also removed? I also tried binding the event to the 'body' and 'document' element, but the event doesn't fire at all then. – Rok Dolinar Dec 09 '19 at 19:03
  • HOWEVER, I'm not sure how am I supposed to rebind the event after the replaceWith()? – Rok Dolinar Dec 09 '19 at 19:16
  • @RokDolinar, do you mean that you tried event delegation? – Jacob Dec 09 '19 at 19:17
  • That should answer your question! Yes, the eventlistener is removed or rather it is attached to an element no longer in the DOM. – Andre Nuechter Dec 09 '19 at 19:20
  • @Jacob I will look into it. For now, I did a hackish solution: I added the event listener creator to the blade file - next to HTML. Now whenever the replaceWith() method is called, the javascript/jquery code is also replaced -> the event listener is thus created again. I guess this is ugly as hell, right? – Rok Dolinar Dec 09 '19 at 19:30

0 Answers0