2

The following chain works:

    $("</p>").html('message').hide().appendTo("#chat").fadeIn()
.parent().scrollTop($('#chat')[0].scrollHeight);

But this doesn't:

    $("</p>").html('message').hide().appendTo("#chat").fadeIn()
.parent().scrollTop($(this)[0].scrollHeight);

this.scrollHeight doesn't work too. How can i get current object reference in jquery chain?

tiktak
  • 1,801
  • 2
  • 26
  • 46

3 Answers3

2

You only get access to the current object inside of a callback. There's no way you can get access to the current object in your chain.

Try this:

var $parent = $("</p>").html('message').hide().appendTo("#chat").fadeIn().parent();
$parent.scrollTop($parent[0].scrollHeight);

If you really don't want to break out of you chain, you can re-select:

$("</p>").html('message').hide().appendTo("#chat").fadeIn()
.parent().scrollTop($("#chat")[0].scrollHeight);

But I'd strongly advise you against it. There's no need to select the same DOM element twice.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
1

In your second code snippet this doesn't point to #chat that's why it doesn't work. this mostly points to the calling function instance or the object which triggered any event.

You can try something like this

var $p = $("</p>").html('message').hide().appendTo("#chat");

$p.fadeIn().parent().scrollTop($p[0].scrollHeight);
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
1

Well, it's obvious. The #chat element is a static element and you are dynamically appending paragraphs to it. Therefore, you want to get a reference to that element beforehand (for instance, on page initialization):

var chat = $( '#chat' )[0];

Now, you do this:

$( '<p />' ).html( 'message' ).hide().appendTo( chat ).fadeIn();
$( chat ).scrollTop( chat.scrollHeight );

So, the idea is to retrieve references to the main static elements (chat-box, toolbar, panel, navigation, etc.) on page initialization, and then use those references all over your application code.

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385