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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

3 Comments

Doesn't $('#chat')[0] return the dom element vs. $('#chat').eq(0) which would return a jquery set?
@DyeA Yes, in my code, chat is a reference to the DOM element. I prefer to keep my references "clean", instead of wrapped in jQuery objects.
Ugh: "Well, it's obvious." It's obviously not obvious to OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.