I can't get Element.scrollIntoView()
to work. I have the code below. There are two locations that it should scroll to, depending on some variable. However, it doesn't scroll to either of them. What am I doing wrong?
class Page extends Component {
scrollToMyRef = (id) => {
var ref = document.getElementById(id);
console.log("Ref1: " + ref); // returns [object HTMLElement]
console.log("Ref2: " + document.ref); // returns undefined
console.log("Id: " + id); // returns myRef
ref.scrollIntoView({
behavior: "smooth",
block: "start",
});
};
componentDidMount() {
if (this.props.location.state) {
if (this.props.location.state.origine) {
this.scrollToMyRef("myRef");
} else {
this.scrollToMyRef("myTopRef");
});
}
}
}
render() {
return (
<div
id="myTopRef"
key="pricing"
className="pricing"
>
...
</div>
<section id=myRef className="section">
...
</section>
...
)
}
#myRef
in an overflowing parent?scrollIntoView
only works if the element itself is outside the viewport + its parent is scrollable. – Axillablock
property, try specifyingnearest
instead ofstart
, but there's no guarantee. I used it in a table a while ago and it works as stated by Terry: only if the element is outside the viewport. – Rakiabehavior: "smooth",
or set it toauto
, my original code works. Any idea why this is? I would like to use the smooth behavior... – Particularism