Monday, May 20, 2024
154
rated 0 times [  157] [ 3]  / answers: 1 / hits: 6600  / 2 Years ago, fri, february 18, 2022, 12:00:00

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>
...
)
}

More From » js-scrollintoview

 Answers
2

After setting a time delay it worked:


scrollToMyRef = (id) => {
var ref = document.getElementById(id);
setTimeout(function () {
ref.scrollIntoView({
behavior: "smooth",
block: "start",
});
}, 100);
};

[#346] Thursday, February 10, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
neildrews

Total Points: 166
Total Questions: 103
Total Answers: 85

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
neildrews questions
Tue, Oct 12, 21, 00:00, 3 Years ago
Tue, Mar 23, 21, 00:00, 3 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
Sun, Jul 12, 20, 00:00, 4 Years ago
;