I’m working on creating a button that sends a customer to the review field in Woocommerce using the scrollIntoView()
function in Javascript.
I’m also working on hiding and showing the button when the reviews section comes into the viewport, and it’s working, but I want to take it a step further. The button as soon as the bottom of the browser hits the ID, which I don’t want. I want the button to show when the ID hits the top of the browser.
Here’s the basic HTML:
<button onClick="scrollToComment()" id="scroll-btn">Leave a Review</button>
<div id="reviews">
//a bunch of reviews and comments go here
<div id="review_form"></div>
</div>
Here is the JS:
window.addEventListener('scroll', function() {
var element = document.querySelector('#reviews');
var position = element.getBoundingClientRect();
var scrollBtn = document.querySelector('#scroll-btn');
if(position.top < window.innerHeight && position.bottom >= 0) {
scrollBtn.style.display = 'block';
}
else {
scrollBtn.style.display = 'none';
}
});
function scrollToComment() {
var button = document.querySelector('#review_form');
button.scrollIntoView();
}
Any help would be appreciated!
2
Answers
Why won’t you just test against the position of the frame when it hits the top ?
Use IntersectionObserver.