-1

I have a little chat app going on. I would like to scroll down to the first unread message. This is what I have:

for i in data.conversation
 $('#chatBox').append("<div class='rrr'>i.message + "-" + i.read</div>")

data.conversation is an object that has a message and a read value. How do I scroll #chatBox all the way down to where i.read equals unread?

msanford
  • 10,127
  • 8
  • 56
  • 83
user2648117
  • 218
  • 1
  • 3
  • 11
  • 3
    Possible duplicate of [jQuery scroll to element](https://stackoverflow.com/questions/6677035/jquery-scroll-to-element) –  Dec 14 '17 at 14:22
  • 1
    Not exactly a duplicate IMHO... Here the element to scroll to is not clearly defined. – miguel-svq Dec 14 '17 at 14:28

2 Answers2

3

You need to "identify" wich element to scroll to. for example, adding a "class" for read/unread:

$('#chatBox').append("<div class='rrr status-" + i.read + "'>i.message + "</div>")

So you can "target" it to scroll there after the loop:

$('html, body').animate({
    scrollTop: $(".status-unread").offset().top
}, 2000);

Check the "possible duplicate" for more information about scrolling.

EDIT: ...check this answer also, it's even closer to you case: jquery Scroll to class name

If you want it to be "inmediate" just change the animation time (2000) to 0... or something much shorter than 2 seconds but still comfortable for the user.

miguel-svq
  • 2,066
  • 7
  • 11
1

You should be able to use jQuery's scrollIntoView() function. For example:

$(".rrr").get(0).scrollIntoView();

In your situation, I think you simply need to give each element in the chatbox an attribute depending on whether i.read equals to true or not. I don't know the rest of your code, but I imagine it would look something like this.

for i in data.conversation
 let msg = $("<div class='rrr'>" + i.message + "</div>");
 if(!(i.read)) {
   msg.attr("class", "unread");
 }
 $('#chatBox').append(msg);

$(".unread").get(0).scrollIntoView();
SindreKjr
  • 247
  • 1
  • 16