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?
The scrollIntoView() method scrolls an element into the visible area of the browser window.
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));
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With