5

I need to do let the last reply scroll into view using jQuery. Here is my code:

function showHideReplies(replies){
 replies.each(function() {
     if($(this).index() < nIniRep || afterReply){
            $(this).show();
            if(afterReply && $(this).index()==replies.length ){
                $(this).scrollIntoView();
            }
        }else{
            $(this).hide();
        }

 });

}

afterReply was defined in my JavaScript.

My question is: I know scrollIntoView() is an HTML DOM Method, and you can use it like this:

var elmnt = document.getElementById("content");
elmnt.scrollIntoView();

But I need to use with jQuery, and I think it should work the same way. But it doesn't work with the jQuery syntax $(this).scrollIntoView();

How do I use scrollIntoView() under jQuery syntax?

Thank you.

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
ChProgrammer
  • 75
  • 1
  • 7
  • 1
    Why not simply do `this.scrollIntoView()`? Also, it may be worth [caching](https://stackoverflow.com/questions/23743326/why-cache-jquery-objects) `$(this)` into a variable. – Karl-André Gagnon Jun 27 '17 at 20:53

1 Answers1

14

jQuery's $(this) returns a jQuery object. To target this element itself, you need to access the first index of the object with [0]. Essentially, jQuery's $(this)[0] is equivalent to JavaScript's this.

As such, you're looking for:

$(this)[0].scrollIntoView();

Hope this helps! :)

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71