Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scrollIntoView() is not a function upon page load?

I have a set of FAQ's where I've hidden the answers by default, leaving only the question, and I've provided a link to each particular question by embedding an id anchor in each so others can link to it.

The question format structure is as follows:

<div class="contents">
   <h1 class="question" id="titleOfQuestion">Some Question Title</h1>
   <div class="answer" id="titleOfQuestion">>
      Some Answer
   </div>
</div>

I need to scroll the question into view upon page load if there's an ID anchor in the URL because div.contents is of a fixed height and often overflows with the property scroll.

Wrapped in a document ready handler, the following code does not work:

if(document.location.hash) {
var id = document.location.hash.substring(1);
    $('div#' + id).scrollIntoView();
}

And I receive the error in Firebug: TypeError: $(...).scrollIntoView is not a function. However, if I then reload the URL from the same location, it does work.

What's going on here?

like image 552
marked-down Avatar asked Jan 05 '14 07:01

marked-down


People also ask

What is scrollIntoView in JavaScript?

The scrollIntoView() method scrolls an element into the visible area of the browser window.

How do I make my scrollIntoView smooth?

Native method: scrollIntoView The usage is simple, just like this: function scroll(e) {e. scrollIntoView({behavior: "smooth", block: "start"});}scroll(document. getElementById(YOUR_DIV_ID));


1 Answers

scrollIntoView is part of the DOM API, not jQuery. You need to run it on an Element, not a jQuery object:

$('div#' + id)[0].scrollIntoView();
like image 51
meagar Avatar answered Nov 05 '22 05:11

meagar