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?

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

Test

var x = document.getElementById('test');
x.scrollIntoView();

see also this plugin

Alright, so here is a solution example:

HTML:

<div id="view1">
    <i onclick="gotoView(1)">View 1</i> | <i onclick="gotoView(2)">View 2</i> | <i onclick="gotoView(3)">View 3</i>
</div>
<div id="view2">
    <i onclick="gotoView(1)">View 1</i> | <i onclick="gotoView(2)">View 2</i> | <i onclick="gotoView(3)">View 3</i>
</div>
<div id="view3">
    <i onclick="gotoView(1)">View 1</i> | <i onclick="gotoView(2)">View 2</i> | <i onclick="gotoView(3)">View 3</i>
</div>

CSS:

div{height:800px; margin:20px; background:#CCC; text-align:center}
i{cursor:pointer; display:inline-block}
i:hover{background:#C00}

JavaScript:

function gotoView(viewId){
    document.getElementById("view" + viewId).scrollIntoView();
    window.location.hash = "view" + viewId;
}

Try this to understand it better.


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   What is the advantage of using Restangular over ngResource?

Similar Posts