Search code examples
javascriptjqueryjquery-scrollablejquery-chaining

Reference to current object in Jquery chain


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?


Solution

  • 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.