Reference to current object in Jquery chain

2.1k Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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.

0
On

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);
3
On

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.